Installation

Install as Agent Plugin Recommended
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install reconciler-logic@skills-hub

Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled). Plugin reconciler-logic v1.0.0 follows the Agent Plugins spec.

Install with the gh extension
gh skills-hub install reconciler-logic

Don't have the extension? Run gh extension install samueltauil/skills-hub first.

Download and extract to your repository:

.github/skills/reconciler-logic/

Extract the ZIP to .github/skills/ in your repo. The folder name must match reconciler-logic for Copilot to auto-discover it.

Skill Files (6)

SKILL.md 6.4 KB
---
name: reconciler-logic
license: Apache-2.0
description: Implement reconcilers and watchers for grafana-app-sdk apps — write `TypedReconciler[*MyKind]` reconcile functions, apply generation-based skip patterns, do conflict-safe status updates via `resource.UpdateObject`, configure `BasicReconcileOptions` (namespace, label/field filters, finalizer management), use `Watcher` for event-style handling, reconcile `UnmanagedKinds` (resources your app doesn't own), and register the whole thing in `app.go`. Use when writing a reconciler, implementing the reconcile loop, adding async business logic, handling create/update/delete events, processing resource state changes, scheduling periodic resyncs with `RequeueAfter`, picking between Watcher and Reconciler, or wiring a controller into `app.go` — even when the user says "process this resource", "handle X events", or "write a controller" without saying "reconciler".
---

# Reconciler Logic

Reconcilers are the async business-logic layer of a grafana-app-sdk app. The SDK enqueues a reconcile event when a resource is created, updated, or deleted; the reconciler observes the current state and drives the system toward the desired state.

## Common Workflows

### Implementing a new reconciler end-to-end

```bash
# 1. Generate operator stubs for a standalone app
grafana-app-sdk project component add operator

# 2. Implement the ReconcileFunc — see § TypedReconciler below for the pattern

# 3. Register the reconciler in app.go (see references/registration.md)

# 4. Generate, build, and verify it runs
grafana-app-sdk generate
go build ./...
go run ./cmd/operator   # tail logs — reconcile entries should appear when you kubectl-apply a resource
```

If the operator starts but no reconcile events fire when you create a resource:
- Check `BasicReconcileOptions.Namespace` matches the resource's namespace
- Check `BasicReconcileOptions.LabelFilters` / `FieldSelectors` — most "no events" issues are filter mismatches (`kubectl get <resource> -o yaml` to see labels)
- Confirm the reconciler was attached to the right (latest) version of the kind

## TypedReconciler — preferred pattern

`operator.TypedReconciler` handles type assertion and provides a strongly-typed `ReconcileFunc`:

```go
type MyKindReconciler struct {
    operator.TypedReconciler[*v1alpha1.MyKind]
    client resource.Client
}

func NewMyKindReconciler(client resource.Client) *MyKindReconciler {
    r := &MyKindReconciler{client: client}
    r.ReconcileFunc = r.reconcile  // wire the typed func
    return r
}

func (r *MyKindReconciler) reconcile(
    ctx context.Context,
    req operator.TypedReconcileRequest[*v1alpha1.MyKind],
) (operator.ReconcileResult, error) {
    obj := req.Object

    // Skip if already reconciled this generation
    if obj.GetGeneration() == obj.Status.LastObservedGeneration &&
       req.Action != operator.ReconcileActionDeleted {
        return operator.ReconcileResult{}, nil
    }

    log := logging.FromContext(ctx).With("name", obj.GetName(), "namespace", obj.GetNamespace())
    log.Info("reconciling", "action", operator.ResourceActionFromReconcileAction(req.Action))

    if req.Action == operator.ReconcileActionDeleted {
        return operator.ReconcileResult{}, nil
    }

    // ... business logic ...

    // Atomic status update — see § Status updates below
    _, err := resource.UpdateObject(ctx, r.client, obj.GetStaticMetadata().Identifier(),
        func(obj *v1alpha1.MyKind, _ bool) (*v1alpha1.MyKind, error) {
            obj.Status.LastObservedGeneration = obj.GetGeneration()
            obj.Status.State = "Ready"
            return obj, nil
        },
        resource.UpdateOptions{Subresource: "status"},
    )
    return operator.ReconcileResult{}, err
}
```

`ReconcileAction` values: `ReconcileActionCreated`, `ReconcileActionUpdated`, `ReconcileActionDeleted`, `ReconcileActionResynced`.

To requeue after a delay (e.g. polling an external system):

```go
return operator.ReconcileResult{RequeueAfter: 10 * time.Second}, nil
```

## Status updates with `resource.UpdateObject`

Always use `resource.UpdateObject` for status writes — it fetches the latest version before applying your update function, avoiding `409 Conflict` errors when multiple reconcile events race:

```go
_, err := resource.UpdateObject(ctx, r.client, identifier,
    func(obj *v1alpha1.MyKind, exists bool) (*v1alpha1.MyKind, error) {
        obj.Status.LastObservedGeneration = obj.GetGeneration()
        obj.Status.State = "Ready"
        obj.Status.Message = ""
        return obj, nil
    },
    resource.UpdateOptions{Subresource: "status"},
)
```

Do **not** use `client.Update` for status — it sends the full object and races with spec changes made by users.

## Generation-based skip

Check `LastObservedGeneration` at the top of the reconcile function to avoid re-processing unchanged resources:

```go
if obj.GetGeneration() == obj.Status.LastObservedGeneration {
    return operator.ReconcileResult{}, nil
}
```

## `ReconcileOptions`

Control informer behavior via `BasicReconcileOptions` on the `AppManagedKind` entry:

```go
{
    Kind:       mykindv1alpha1.MyKindKind(),
    Reconciler: reconciler,
    ReconcileOptions: simple.BasicReconcileOptions{
        Namespace:      "my-namespace",          // watch one namespace; default is all
        LabelFilters:   []string{"env=prod"},    // only reconcile matching resources
        FieldSelectors: []string{"status.phase=Running"},
        UsePlain:       false,                   // false = wrap in OpinionatedReconciler (default; manages finalizers)
    },
},
```

`UsePlain: false` (the default) wraps your reconciler in `OpinionatedReconciler`, which manages finalizers automatically so the SDK can guarantee clean deletion.

## References

- [`references/watchers.md`](references/watchers.md) — `Watcher` alternative (event-style Add/Update/Delete callbacks) + decision matrix for watcher vs reconciler
- [`references/unmanaged-kinds.md`](references/unmanaged-kinds.md) — `UnmanagedKinds` for reconciling resources your app doesn't own, with `UseOpinionated: false` guidance and common failure modes
- [`references/registration.md`](references/registration.md) — full `app.go` wiring (client setup, multi-version registration, `ValidateManifest`) + common failure modes

## External resources

- [grafana-app-sdk GitHub](https://github.com/grafana/grafana-app-sdk)
- [operator package docs](https://pkg.go.dev/github.com/grafana/grafana-app-sdk/operator)
references/
informer-configuration.md 12.0 KB
# Informer Configuration

Reconcilers and Watchers receive events from an Informer, and both together are managed by an informer controller.
The configuration of this controller created by `simple.App` is done in `simple.AppConfig.InformerConfig`.

## InformerConfig

`simple.AppConfig.InformerConfig` is of type `simple.AppInformerConfig`, which is defined as:
```go
// AppInformerConfig contains configuration for the App's internal operator.InformerController
type AppInformerConfig struct {
	// InformerOptions are the options for the informer.
	InformerOptions operator.InformerOptions
	// RetryPolicy is the policy for retrying events.
	RetryPolicy operator.RetryPolicy
	// RetryDequeuePolicy is the policy for dequeuing events.
	RetryDequeuePolicy operator.RetryDequeuePolicy
	// FinalizerSupplier is used to generate the finalizer for the kind.
	FinalizerSupplier operator.FinalizerSupplier
	// InProgressFinalizerSupplier is used to generate the "in-progress" finalizer used by opinionated adds,
	// before the "normal" finalizer (provided by FinalizerSupplier) is applied when the add completes successfully.
	// By default, this is "<app name>-wip"
	InProgressFinalizerSupplier operator.FinalizerSupplier
	// InformerSupplier can be set to specify a function for creating informers for kinds.
	// If left unset, DefaultInformerSupplier will be used.
	InformerSupplier InformerSupplier
}
```
`operator.InformerOptions` is defined as
```go
// InformerOptions are generic options for all Informer implementations.
type InformerOptions struct {
	// ListWatchOptions are the options for filtering the watch based on namespace and other compatible filters.
	ListWatchOptions ListWatchOptions
	// CacheResyncInterval is the interval at which the informer will emit CacheResync events for all resources in the cache.
	// This is distinct from a full resync, as no information is fetched from the API server.
	// Changes to this value after run() is called will not take effect.
	// An empty value will disable cache resyncs.
	CacheResyncInterval time.Duration
	// EventTimeout is the timeout for an event to be processed.
	// If an event is not processed within this timeout, it will be dropped.
	// The timeout cannot be larger than the cache resync interval, if it is,
	// the cache resync interval will be used instead.
	// An empty value will disable event timeouts.
	EventTimeout time.Duration
	// ErrorHandler is called if the informer encounters an error which does not stop the informer from running,
	// but may stop it from processing a given event.
	ErrorHandler func(context.Context, error)
	// HealthCheckIgnoreSync will set the KubernetesBasedInformer HealthCheck to return ok once the informer is started,
	// rather than waiting for the informer to finish with its initial list sync.
	// You may want to set this to `true` if you have a particularly long initial sync period and don't want readiness checks failing.
	HealthCheckIgnoreSync bool
	// UseWatchList if turned on instructs the reflector to open a stream to bring data from the API server.
	// Streaming has the primary advantage of using fewer server's resources to fetch data.
	//
	// The old behavior establishes a LIST request which gets data in chunks.
	// Paginated list is less efficient and depending on the actual size of objects
	// might result in an increased memory consumption of the APIServer.
	//
	// Defaults to false. Requires Kubernetes 1.27+ when enabled.
	// See https://github.com/kubernetes/enhancements/tree/master/keps/sig-api-machinery/3157-watch-list#design-details
	UseWatchList bool
	// WatchListPageSize is the requested chunk size for paginated LIST operations.
	// This significantly reduces memory usage when watching large numbers of objects (>10K).
	// Recommended values: 5000-10000 for most use cases.
	// Note: This only affects traditional LIST operations. It does NOT apply to watch-list streaming (UseWatchList).
	// An empty value (0) will use client-go's default pagination behavior based on resource version.
	WatchListPageSize int64
	// MaxConcurrentWorkers is the maximum number of concurrent workers for event processing in ConcurrentInformer.
	// Each worker maintains a queue of events which are processed sequentially.
	// Events for a particular object are assigned to the same worker to maintain in-order delivery per object.
	// An empty value (0) will use the default of 10 workers.
	MaxConcurrentWorkers uint64
}
```

## Error Handling

If `AppInformerConfig.InformerOptions.ErrorHandler` is defined, it will be called prior to requeuing an error returned from a watcher or reconciler. By default, this is a function which logs the error to the logger from the context.

## Retries and Dequeuing

`simple.App` internally manages retries and dequeueing of reconcile events. If a watcher or reconciler call returns an error, it is automatically retried based on the `RetryPolicy`. When a new event for the same resource arrives while a retry is still in the queue, the retry may be dequeued per the `RetryDequeuePolicy`.

`RetryPolicy` is defined as
```go
// RetryPolicy is a function that defines whether an event should be retried, based on the error and number of attempts.
// It returns a boolean indicating whether another attempt should be made, and a time.Duration after which that attempt should be made again.
type RetryPolicy func(err error, attempt int) (bool, time.Duration)
```
If unspecified, `AppInformerConfig.RetryPolicy` defaults to an exponential backoff retry policy (`operator.DefaultRetryPolicy`) that retries a total of five times before giving up. 

`operator.ExponentialBackoffRetryPolicy(initialDelay time.Duration, maxAttempts int)` can be used to create an arbitrary exponential backoff retry policy.

Custom retry policies may want to interrogate the supplied error to determine if a retry should be performed.

Dequeuing existing retries is managed with `AppInformerConfig.RetryDequeuePolicy`. A `RetryDequeuePolicy` is a function defined as:
```go
// RetryDequeuePolicy is a function that defines when a retry should be dequeued when a new action is taken on a resource.
// It accepts information about the new action being taken, and information about the current queued retry,
// and returns `true` if the retry should be dequeued.
// A RetryDequeuePolicy may be called multiple times for the same action, depending on the number of pending retries for the object.
type RetryDequeuePolicy func(newAction ResourceAction, newObject resource.Object, retryAction ResourceAction, retryObject resource.Object, retryError error) bool
```
If unspecified, it uses the default (`operator.OpinionatedRetryDequeuePolicy`) that is defined as
```go
// OpinionatedRetryDequeuePolicy is a RetryDequeuePolicy which has the following logic:
// 1. If the newAction is a delete, dequeue the retry
// 2. If the newAction and retryAction are different, keep the retry (for example, a queued create retry, and a received update action)
// 3. If the generation of newObject and retryObject is the same, keep the retry
// 4. Otherwise, dequeue the retry
var OpinionatedRetryDequeuePolicy = func(newAction ResourceAction, newObject resource.Object, retryAction ResourceAction, retryObject resource.Object, _ error) bool {
	if newAction == ResourceActionDelete {
		return true
	}
	if newAction != retryAction {
		return false
	}
	if newObject.GetGeneration() == retryObject.GetGeneration() {
		return false
	}
	return true
}
```

## Finalizer Suppliers

Both the `OpinionatedReconciler` and `OpinionatedWatcher` manage finalizers, and the names of the finalizers are supplied by `AppInformerConfig.FinalizerSupplier` and `AppInformerConfig.InProgressFinalizerSupplier`.

An `operator.FinalizerSupplier` is defined as
```go
// FinalizerSupplier represents a function that creates string finalizer from provider schema.
type FinalizerSupplier func(sch resource.Schema) string
```
By default, `operator.DefaultFinalizerSupplier` and `operator.InProgressFinalizerSupplier` are used, defined as:
```go
// DefaultFinalizerSupplier crates finalizer following to pattern `operator.{version}.{kind}.{group}`.
func DefaultFinalizerSupplier(sch resource.Schema) string {
	return fmt.Sprintf("operator.%s.%s.%s", sch.Version(), sch.Kind(), sch.Group())
}

func InProgressFinalizerSupplier(sch resource.Schema) string {
	return fmt.Sprintf("wip.%s.%s.%s", sch.Version(), sch.Kind(), sch.Group())
}
```
The in-progress finalizer is added upon event ingestion by an `OpinionatedReconciler` or `OpinionatedWatcher` if no finalizer is present, and is replaced by the normal finalizer when the downstream request succeeds.

## InformerSupplier

`InformerSupplier` is defined as
```go
// InformerSupplier is a function which creates an operator.Informer for a kind, given a ClientGenerator and ListWatchOptions
type InformerSupplier func(
	kind resource.Kind, clients resource.ClientGenerator, options operator.InformerOptions,
) (operator.Informer, error)
```
and uses the following default if not overridden:
```go
// DefaultInformerSupplier is a default InformerSupplier function which creates a basic operator.KubernetesBasedInformer.
// Note: This supplier does NOT respect WatchListPageSize or UseWatchList configuration.
// For memory-optimized informers that support these options, use OptimizedInformerSupplier instead.
var DefaultInformerSupplier = func(
	kind resource.Kind, clients resource.ClientGenerator, options operator.InformerOptions,
) (operator.Informer, error) {
	client, err := clients.ClientFor(kind)
	if err != nil {
		return nil, err
	}

	inf, err := operator.NewKubernetesBasedInformer(kind, client, options)
	if err != nil {
		return nil, err
	}

	return operator.NewConcurrentInformerFromOptions(inf, options)
}
```
It is used when `simple.App` creates a new `Informer` for a kind if a watcher or reconciler are configured for it. This allows the user to swap in different `Informer` implementations if they wish. The `operator` package has an alternate informer that can use a custom (and therefore not in-memory like the `KubernetesBasedInformer`) cache, using `NewCustomCacheInformer`, and an implementation of this using memcached as the storage with `NewMemcachedInformer`.

By default, the `KubernetesBasedInformer`, which uses kubernetes' `cache.NewSharedIndexInformer` under the hood, is wrapped in `operator.NewConcurrentInformerFromOptions`, which allows for concurrent event processing (as opposed to the standard kubernetes informer logic, where all events are placed in a queue and processed one by one). This concurrency guarantees that events for the same resource will be processed in sequence by the same goroutine, but otherwise will spread informer events across a configured number of goroutines to allow for faster processing of events, particularly at startup, when all resources currently in the APIServer must be processed before the informer will begin processing new events.

### OptimizedInformerSupplier

`simple.OptimizedInformerSupplier` is an alternative to `DefaultInformerSupplier` that fully respects the `WatchListPageSize` and `UseWatchList` options in `InformerOptions`. The default supplier ignores these settings. Use it when watching large numbers of objects (>10K) or in memory-constrained environments:

```go
simple.AppConfig{
    InformerConfig: simple.AppInformerConfig{
        InformerSupplier: simple.OptimizedInformerSupplier,
        InformerOptions: operator.InformerOptions{
            UseWatchList:      true,  // streaming, requires Kubernetes 1.27+
            WatchListPageSize: 5000,  // chunk size for paginated LIST fallback
        },
    },
    // ...
}
```

`OptimizedInformerSupplier` is marked experimental and may change in future releases.

## Health Checks

By default, the health check returned by an `Informer` will not return healthy until all start-up events have been processed. While the `ConcurrentInformer` makes this faster, there may be scenarios where this start-up time is still too lengthy and having the pod be unhealthy for that start-up duration will cause it to be killed. In that case, `AppInformerConfig.InformerOptions.HealthCheckIgnoreSync` can be set to `true` to have the health check return healthy so long as the informer is running.
reconciler-patterns.md 9.7 KB
# Reconciler Patterns

## Finalizers

Use finalizers to ensure cleanup of external resources before a Kubernetes resource is deleted. Without a finalizer, the resource may be deleted before the reconciler has a chance to clean up. Finalizers are automatically managed by the `OpinionatedReconciler` and `OpinionatedWatcher`, but can be manually managed if preferred:

```go
const myKindFinalizer = "my-app.grafana.app/finalizer"

func (r *MyKindReconciler) reconcile(
    ctx context.Context,
    req operator.TypedReconcileRequest[*v1.MyKind],
) (operator.ReconcileResult, error) {
    obj := req.Object

    // Handle deletion
    if obj.DeletionTimestamp != nil {
        if containsString(obj.Finalizers, myKindFinalizer) {
            // Run cleanup
            if err := r.cleanupExternalResources(ctx, obj); err != nil {
                return operator.ReconcileResult{}, fmt.Errorf("cleanup: %w", err)
            }
            // Remove finalizer
            obj.Finalizers = removeString(obj.Finalizers, myKindFinalizer)
            if _, err := r.client.Update(ctx, obj, resource.UpdateOptions{}); err != nil {
                return operator.ReconcileResult{}, fmt.Errorf("removing finalizer: %w", err)
            }
        }
        return operator.ReconcileResult{}, nil
    }

    // Add finalizer on first reconcile
    if !containsString(obj.Finalizers, myKindFinalizer) {
        obj.Finalizers = append(obj.Finalizers, myKindFinalizer)
        if _, err := r.client.Update(ctx, obj, resource.UpdateOptions{}); err != nil {
            return operator.ReconcileResult{}, fmt.Errorf("adding finalizer: %w", err)
        }
        // Return early — the update will trigger another reconcile
        return operator.ReconcileResult{}, nil
    }

    // ... normal reconcile logic ...
}

func containsString(slice []string, s string) bool {
    for _, item := range slice {
        if item == s { return true }
    }
    return false
}

func removeString(slice []string, s string) []string {
    result := make([]string, 0, len(slice))
    for _, item := range slice {
        if item != s { result = append(result, item) }
    }
    return result
}
```

When managing finalizers manually, be sure to set `UsePlain: true` for the ManagedKind's `ReconcileOptions`.

## Polling External Systems with RequeueAfter

When an external operation is asynchronous, poll until it completes:

```go
func (r *MyKindReconciler) reconcile(
    ctx context.Context,
    req operator.TypedReconcileRequest[*v1.MyKind],
) (operator.ReconcileResult, error) {
    obj := req.Object

    switch obj.Status.State {
    case "", "Pending":
        // Kick off the async operation
        jobID, err := r.externalClient.StartJob(ctx, buildJobSpec(obj))
        if err != nil {
            return operator.ReconcileResult{}, fmt.Errorf("starting job: %w", err)
        }
        _, err = resource.UpdateObject(ctx, r.client, obj.GetStaticMetadata().Identifier(),
            func(o *v1.MyKind, _ bool) (*v1.MyKind, error) {
                o.Status.State = "Provisioning"
                o.Status.ExternalJobID = jobID
                return o, nil
            },
            resource.UpdateOptions{Subresource: "status"},
        )
        if err != nil {
            return operator.ReconcileResult{}, err
        }
        // Check back in 10 seconds
        return operator.ReconcileResult{RequeueAfter: 10 * time.Second}, nil

    case "Provisioning":
        status, err := r.externalClient.GetJobStatus(ctx, obj.Status.ExternalJobID)
        if err != nil {
            return operator.ReconcileResult{}, fmt.Errorf("checking job status: %w", err)
        }
        var newState, newMessage string
        switch status {
        case "running":
            return operator.ReconcileResult{RequeueAfter: 10 * time.Second}, nil
        case "done":
            newState = "Ready"
        case "failed":
            newState = "Error"
            newMessage = "External job failed"
        default:
            return operator.ReconcileResult{}, fmt.Errorf("unknown provisioning status '%s'", status)
        }
        _, err = resource.UpdateObject(ctx, r.client, obj.GetStaticMetadata().Identifier(),
            func(o *v1.MyKind, _ bool) (*v1.MyKind, error) {
                o.Status.State = newState
                o.Status.Message = newMessage
                return o, nil
            },
            resource.UpdateOptions{Subresource: "status"},
        )
        return operator.ReconcileResult{}, err

    case "Ready":
        // Ensure still in sync
        return r.reconcileReady(ctx, obj)
    }

    return operator.ReconcileResult{}, nil
}
```

## Atomic Status Updates with resource.UpdateObject

Use `resource.UpdateObject` to update status — it fetches the latest version of the object, applies your update function, then pushes the result. This avoids `409 Conflict` errors that occur when a reconcile event races with a user spec change:

```go
_, err := resource.UpdateObject(ctx, r.client, req.Object.GetStaticMetadata().Identifier(),
    func(obj *v1alpha1.MyKind, exists bool) (*v1alpha1.MyKind, error) {
        obj.Status.LastObservedGeneration = req.Object.GetGeneration()
        obj.Status.State = "Ready"
        obj.Status.Message = ""
        return obj, nil
    },
    resource.UpdateOptions{Subresource: "status"},
)
```

Never use `client.Update` for status — it sends the full object body and conflicts with concurrent spec writes.

## Generation-Based Status Staleness

Set `LastObservedGeneration` after successfully reconciling a generation. Consumers can check `status.lastObservedGeneration == metadata.generation` to know if the status is current:

```go
obj.Status.LastObservedGeneration = obj.GetGeneration()
```

Skip reconciliation entirely if already processed. Note this also skips `ReconcileActionResynced` events for unchanged resources — this is intentional when you only want to react to spec changes:

```go
if obj.GetGeneration() == obj.Status.LastObservedGeneration {
    return operator.ReconcileResult{}, nil
}
```

## Structured Logging

```go
func (r *MyKindReconciler) reconcile(
    ctx context.Context,
    req operator.TypedReconcileRequest[*v1.MyKind],
) (operator.ReconcileResult, error) {
    log := logging.FromContext(ctx).With(
        "name", req.Object.GetName(),
        "namespace", req.Object.GetNamespace(),
        "generation", req.Object.GetGeneration(),
    )

    log.Info("Starting reconcile")

    if err := r.doWork(ctx, req.Object); err != nil {
        log.Error("Reconcile failed", "error", err)
        return operator.ReconcileResult{}, err
    }

    log.Info("Reconcile complete")
    return operator.ReconcileResult{}, nil
}
```

## Permanent vs Transient Errors

```go
// Mark permanent errors in status and stop retrying
type PermanentError struct{ msg string }
func (e PermanentError) Error() string { return e.msg }

func (r *MyKindReconciler) reconcile(
    ctx context.Context,
    req operator.TypedReconcileRequest[*v1.MyKind],
) (operator.ReconcileResult, error) {
    obj := req.Object
    if err := r.doWork(ctx, obj); err != nil {
        var permErr PermanentError
        if errors.As(err, &permErr) {
            // Update status and don't retry
            msg := permErr.Error()
            _, _ = resource.UpdateObject(ctx, r.client, obj.GetStaticMetadata().Identifier(),
                func(o *v1.MyKind, _ bool) (*v1.MyKind, error) {
                    o.Status.State = "Error"
                    o.Status.Message = msg
                    return o, nil
                },
                resource.UpdateOptions{Subresource: "status"},
            )
            return operator.ReconcileResult{}, nil // nil error = no retry
        }
        // Transient error — SDK will retry with backoff
        return operator.ReconcileResult{}, fmt.Errorf("transient error: %w", err)
    }
    return operator.ReconcileResult{}, nil
}
```

## Testing Reconcilers

The SDK does not ship fake client implementations. Implement the `resource.Client` interface in your test package as needed. A minimal stub only needs to implement the methods your reconciler actually calls:

```go
type fakeClient struct {
    objects map[string]*v1.MyKind
    updated *v1.MyKind
}

func (f *fakeClient) Get(ctx context.Context, id resource.Identifier) (resource.Object, error) {
    obj, ok := f.objects[id.Name]
    if !ok {
        return nil, fmt.Errorf("not found")
    }
    return obj, nil
}

func (f *fakeClient) Update(ctx context.Context, id resource.Identifier, obj resource.Object, opts resource.UpdateOptions) (resource.Object, error) {
    typed := obj.(*v1.MyKind)
    f.updated = typed
    f.objects[id.Name] = typed
    return typed, nil
}

// Implement remaining resource.Client methods as no-ops or panics.

func TestMyKindReconciler_Reconcile(t *testing.T) {
    obj := &v1.MyKind{
        ObjectMeta: metav1.ObjectMeta{
            Name:      "test",
            Namespace: "default",
        },
        Spec: v1.MyKindSpec{Title: "Test"},
    }

    client := &fakeClient{objects: map[string]*v1.MyKind{"test": obj}}
    fakeExternal := &fakeExternalClient{}

    r := NewMyKindReconciler(client)
    r.externalClient = fakeExternal

    result, err := r.reconcile(context.Background(), operator.TypedReconcileRequest[*v1.MyKind]{
        Object: obj,
        Action: operator.ReconcileActionCreated,
    })

    assert.NoError(t, err)
    assert.Equal(t, operator.ReconcileResult{}, result)
    assert.Equal(t, "Ready", client.updated.Status.State)
}
```

## Context Usage

Always propagate context from `Reconcile` to all downstream calls. Never create a new background context:

```go
// Good
result, err := r.externalClient.DoWork(ctx, params)

// Bad — loses deadline, cancellation, and trace context
result, err := r.externalClient.DoWork(context.Background(), params)
```
registration.md 2.5 KB
# Registration in `app.go`

How to wire your reconciler into the app's `New` function.

```go
func New(cfg app.Config) (app.App, error) {
    cfg.KubeConfig.APIPath = "/apis"

    // 1. Build a client for the kind your reconciler operates on
    client, err := k8s.NewClientRegistry(cfg.KubeConfig, k8s.DefaultClientConfig()).
        ClientFor(mykindv1alpha2.MyKindKind())
    if err != nil {
        return nil, fmt.Errorf("creating client: %w", err)
    }

    // 2. Register the kind with reconciler attached to the latest version only
    a, err := simple.NewApp(simple.AppConfig{
        Name:       "my-app",
        KubeConfig: cfg.KubeConfig,
        ManagedKinds: []simple.AppManagedKind{
            {
                // Older version: validation + mutation only
                Kind:      mykindv1alpha1.MyKindKind(),
                Validator: NewValidator(),
                Mutator:   NewMutator(),
            },
            {
                // Latest version: validation + mutation + reconciler
                Kind:       mykindv1alpha2.MyKindKind(),
                Reconciler: NewMyKindReconciler(client),
                Validator:  NewValidator(),
                Mutator:    NewMutator(),
            },
        },
    })
    if err != nil {
        return nil, fmt.Errorf("error creating app: %w", err)
    }

    // 3. Validate the AppManifest matches what's registered (catches missing route handlers etc.)
    if err = a.ValidateManifest(cfg.ManifestData); err != nil {
        return nil, fmt.Errorf("app manifest validation failed: %w", err)
    }
    return a, nil
}
```

## Why attach the reconciler only to the latest version

With multi-version kinds, the reconciler should only fire on the canonical/latest version. The SDK auto-converts incoming objects via the conversion webhook, so reconciling v1alpha1 and v1alpha2 separately would double-reconcile the same resource.

## Common failure modes

| Symptom | Likely cause |
|---|---|
| `app manifest validation failed: route handler missing` | A `routes:` entry in CUE has no Go handler registered. Add `app.RegisterCustomRouteHandler("<routeName>", handler)` before `ValidateManifest`. |
| Reconciler doesn't fire on resource creates | The reconciler is attached to the wrong version, or `UsePlain: true` was set on `BasicReconcileOptions` and finalizers aren't being managed. |
| `error creating client: ...` | Wrong API path or kube config — check `cfg.KubeConfig.APIPath = "/apis"` is set before building the client. |
unmanaged-kinds.md 1.7 KB
# UnmanagedKinds — watching kinds your app doesn't own

To reconcile a kind your app doesn't own (e.g. a `ConfigMap`, or a kind owned by another app), use `UnmanagedKinds` in `AppConfig`:

```go
UnmanagedKinds: []simple.AppUnmanagedKind{
    {
        Kind:       corev1.ConfigMapKind(),
        Reconciler: &ConfigMapReconciler{},
        ReconcileOptions: simple.UnmanagedKindReconcileOptions{
            Namespace:      "my-namespace",
            LabelFilters:   []string{"app=my-app"},
            UseOpinionated: false,  // don't add finalizers to unmanaged resources
        },
    },
},
```

## Why `UseOpinionated: false` for unmanaged kinds

The `OpinionatedReconciler` adds finalizers so the SDK can guarantee clean deletion. For **managed** kinds that's correct — the app owns the resource lifecycle. For **unmanaged** kinds (resources owned by another app or the cluster itself), adding finalizers is invasive: it makes deletion of the resource dependent on your app being healthy, which can leave orphan finalizers if your app is uninstalled while resources exist.

Default to `UseOpinionated: false` for `UnmanagedKinds` unless you genuinely need finalizer-driven cleanup for the unmanaged resource.

## Common failure modes

| Symptom | Likely cause |
|---|---|
| Reconciler doesn't fire | Label filter doesn't match the resource's labels (check `kubectl get <resource> -o yaml` for labels) |
| Permission errors at startup | Your app's ServiceAccount lacks RBAC on the unmanaged kind — add a Role binding for `get`/`list`/`watch` on the kind's API group |
| Resources stuck in deletion | `UseOpinionated: true` was set; finalizer wasn't removed before app uninstall. Patch the resource to remove the finalizer manually. |
watchers.md 1.4 KB
# Watcher — alternative to Reconciler

A `Watcher` receives distinct `Add` / `Update` / `Delete` callbacks instead of a unified reconcile loop. Reconcilers are the preferred pattern; the default scaffolding still uses watchers because they're simpler for event-style handling.

```go
type MyKindWatcher struct {
    client resource.Client
}

func (w *MyKindWatcher) Add(ctx context.Context, obj resource.Object) error {
    typed := obj.(*v1alpha1.MyKind)
    // handle create
    return nil
}

func (w *MyKindWatcher) Update(ctx context.Context, obj, old resource.Object) error {
    typed := obj.(*v1alpha1.MyKind)
    // handle update
    return nil
}

func (w *MyKindWatcher) Delete(ctx context.Context, obj resource.Object) error {
    // handle delete
    return nil
}

func (w *MyKindWatcher) Sync(ctx context.Context, obj resource.Object) error {
    // called on resync; handle like Add if needed
    return nil
}
```

## Picking watcher vs reconciler

| Use a Reconciler when… | Use a Watcher when… |
|---|---|
| Logic is mostly "drive toward desired state" | Each event needs distinct handling (e.g. notify on Create, archive on Delete) |
| You want generation-based skip + status updates | You don't track convergence to desired state |
| You need RequeueAfter for polling external systems | You don't need scheduled re-runs |

Register the watcher in `AppManagedKind` using the `Watcher` field instead of `Reconciler` (see [references/registration.md](registration.md)).

License (Apache-2.0)

View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/grafana/skills/blob/main/LICENSE