npm package: @qrvey/cluster-sdk
Description: A TypeScript SDK for managing Kubernetes resources including cluster clients, secrets, and container registry operations
Author: Qrvey
Latest version: 1.0.0-654

# @qrvey/cluster-sdk

![install size](https://packagephobia.now.sh/badge?p=%40qrvey%2Fcluster-sdk)
![coverage](https://img.shields.io/badge/unit_test_coverage-98%25-brightgreen)

**@qrvey/cluster-sdk** is a TypeScript library for interacting with Kubernetes cluster resources from Node.js applications. It provides services to manage Kubernetes clients, read secrets, extract registry credentials, and verify container image availability in registries.

## Features

-   Read and parse Kubernetes secrets
-   Extract Docker registry credentials from secrets
-   Verify container image existence in registries

## Installation

```bash
npm install @qrvey/cluster-sdk
```

or

```bash
yarn add @qrvey/cluster-sdk
```

## Prerequisites

This library requires access to a Kubernetes cluster. It uses the Kubernetes client configuration from the default location (typically `~/.kube/config` or in-cluster config when running inside a pod).

### Optional Environment Variables

The following environment variables are optional and provide defaults for certain operations:

-   `JOB_NAMESPACE` - Default namespace for secret operations (default: `'qrveyapps-jobs'`)
-   `JOB_IMAGE_PULL_SECRET_NAME` - Default secret name for registry credentials (default: `'regcred'`)

## Usage

### ClusterClientService

Base service that provides access to Kubernetes API clients.

```typescript
import { ClusterClientService } from '@qrvey/cluster-sdk';

const clusterClient = new ClusterClientService();

// Get CoreV1Api client for core Kubernetes resources
const coreApi = clusterClient.getCoreV1Api();

// Get BatchV1Api client for batch resources (jobs, cronjobs)
const batchApi = clusterClient.getBatchV1Api();

// Get KubeConfig instance
const kubeConfig = clusterClient.getKubeConfig();
```

### SecretControllerService

Service for reading and parsing Kubernetes secrets, particularly Docker registry credentials.

```typescript
import {
    ClusterClientService,
    SecretControllerService,
} from '@qrvey/cluster-sdk';

const clusterClient = new ClusterClientService();
const secretController = new SecretControllerService(clusterClient);

// Read a secret
const secret = await secretController.getSecret('my-namespace', 'my-secret');

// Extract registry credentials from a Docker config secret
const credentials = await secretController.getRegistryCredentialsFromSecret(
    'my-namespace',
    'regcred',
);

console.log(credentials);
// {
//   username: 'my.user',
//   password: 'my.password',
//   registry: 'https://myregistry.azurecr.io'
// }
```

### RegistryImageService

Service for verifying container image availability in registries using credentials from Kubernetes secrets.

#### Check Single Image

```typescript
import { ClusterClientService, RegistryImageService } from '@qrvey/cluster-sdk';

const clusterClient = new ClusterClientService();
const registryImageService = new RegistryImageService(clusterClient);

// Check if an image exists in a registry
const exists = await registryImageService.imageExists(
    'https://myregistry.azurecr.io',
    'my-image',
    'v1.0.0',
    'my-namespace', // optional, uses JOB_NAMESPACE env var if not provided
    'regcred', // optional, uses JOB_IMAGE_PULL_SECRET_NAME env var if not provided
);

console.log(exists); // true or false
```

#### Check Multiple Images

```typescript
import { ClusterClientService, RegistryImageService } from '@qrvey/cluster-sdk';

const clusterClient = new ClusterClientService();
const registryImageService = new RegistryImageService(clusterClient);

const imagesToCheck = [
    {
        registryUrl: 'https://myregistry.azurecr.io',
        imageName: 'app-backend',
        imageTag: 'v1.0.0',
    },
    {
        registryUrl: 'https://myregistry.azurecr.io',
        imageName: 'app-frontend',
        imageTag: 'v1.0.0',
    },
];

const results = await registryImageService.checkImages(
    imagesToCheck,
    'my-namespace', // optional
    'regcred', // optional
);

console.log(results);
// [
//   { registryUrl: '...', imageName: 'app-backend', imageTag: 'v1.0.0', exists: true },
//   { registryUrl: '...', imageName: 'app-frontend', imageTag: 'v1.0.0', exists: false }
// ]
```

## Error Handling

The library provides custom error classes for better error handling:

```typescript
import {
    ClusterSDKError,
    SecretError,
    RegistryError,
} from '@qrvey/cluster-sdk';

try {
    const credentials = await secretController.getRegistryCredentialsFromSecret(
        'my-namespace',
        'regcred',
    );
} catch (error) {
    if (error instanceof SecretError) {
        console.error('Secret error:', error.message);
        console.error('Secret name:', error.toJSON().details.secretName);
        console.error('Namespace:', error.toJSON().details.namespace);
    } else if (error instanceof RegistryError) {
        console.error('Registry error:', error.message);
        console.error('Registry:', error.toJSON().details.registry);
    }
}
```

## API Reference

### ClusterClientService

-   `getCoreV1Api()` - Returns CoreV1Api instance for Kubernetes core resources
-   `getBatchV1Api()` - Returns BatchV1Api instance for batch resources
-   `getKubeConfig()` - Returns KubeConfig instance

### SecretControllerService

-   `getSecret(namespace: string, secretName: string): Promise<V1Secret>` - Reads a Kubernetes secret
-   `getRegistryCredentialsFromSecret(namespace: string, secretName: string): Promise<RegistryCredentials>` - Extracts Docker registry credentials from a secret

### RegistryImageService

-   `imageExists(registryUrl: string, imageName: string, tag: string, namespace?: string, secretName?: string): Promise<boolean>` - Checks if an image exists in a registry
-   `checkImages(images: IServiceImageReference[], namespace?: string, secretName?: string): Promise<Array<IServiceImageReference & { exists: boolean }>>` - Checks multiple images in batch