This commit is contained in:
Morten Olsen
2025-07-28 22:27:40 +02:00
parent b35782a7d8
commit 48f1bde404
25 changed files with 3341 additions and 235 deletions

18
.prettierrc.json Normal file
View File

@@ -0,0 +1,18 @@
{
"arrowParens": "always",
"bracketSpacing": true,
"htmlWhitespaceSensitivity": "css",
"insertPragma": false,
"bracketSameLine": false,
"jsxSingleQuote": false,
"printWidth": 120,
"proseWrap": "preserve",
"quoteProps": "as-needed",
"requirePragma": false,
"semi": true,
"singleQuote": true,
"tabWidth": 2,
"trailingComma": "all",
"useTabs": false,
"singleAttributePerLine": false
}

14
.u8.json Normal file
View File

@@ -0,0 +1,14 @@
{
"values": {
"monoRepo": false
},
"entries": [
{
"timestamp": "2025-07-28T20:25:00.416Z",
"template": "eslint",
"values": {
"monoRepo": false
}
}
]
}

51
eslint.config.mjs Normal file
View File

@@ -0,0 +1,51 @@
import { FlatCompat } from '@eslint/eslintrc';
import importPlugin from 'eslint-plugin-import';
import eslint from '@eslint/js';
import eslintConfigPrettier from 'eslint-config-prettier';
import tseslint from 'typescript-eslint';
const compat = new FlatCompat({
baseDirectory: import.meta.__dirname,
resolvePluginsRelativeTo: import.meta.__dirname,
});
export default tseslint.config(
eslint.configs.recommended,
...tseslint.configs.strict,
...tseslint.configs.stylistic,
eslintConfigPrettier,
{
files: ['**/*.{ts,tsxx}'],
extends: [importPlugin.flatConfigs.recommended, importPlugin.flatConfigs.typescript],
rules: {
'import/no-unresolved': 'off',
'import/extensions': ['error', 'ignorePackages'],
'import/exports-last': 'error',
'import/no-default-export': 'error',
'import/order': [
'error',
{
groups: ['builtin', 'external', 'internal', 'parent', 'sibling', 'index'],
'newlines-between': 'always',
},
],
'import/no-duplicates': 'error',
},
},
{
rules: {
'@typescript-eslint/consistent-type-definitions': ['error', 'type'],
},
},
{
files: ['**.d.ts'],
rules: {
'@typescript-eslint/triple-slash-reference': 'off',
'@typescript-eslint/consistent-type-definitions': 'off',
},
},
...compat.extends('plugin:prettier/recommended'),
{
ignores: ['**/node_modules/', '**/dist/', '**/.turbo/', '**/generated/'],
},
);

View File

@@ -5,7 +5,17 @@
"private": true,
"devDependencies": {
"@types/bun": "latest",
"nodemon": "^3.1.10"
"nodemon": "^3.1.10",
"@eslint/eslintrc": "3.3.1",
"@eslint/js": "9.32.0",
"@pnpm/find-workspace-packages": "6.0.9",
"eslint": "9.32.0",
"eslint-config-prettier": "10.1.8",
"eslint-plugin-import": "2.32.0",
"eslint-plugin-prettier": "5.5.3",
"prettier": "3.6.2",
"typescript": "5.8.3",
"typescript-eslint": "8.38.0"
},
"peerDependencies": {
"typescript": "^5"
@@ -22,5 +32,8 @@
"onlyBuiltDependencies": [
"sqlite3"
]
},
"scripts": {
"test:lint": "eslint"
}
}

3046
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,10 +1,8 @@
apiVersion: 'homelab.mortenolsen.pro/v1'
kind: 'PostgresDatabase'
metadata:
name: 'test2'
namespace: 'playground'
labels:
foo: 'bar'
annotations:
foo: 'bar'
spec: {}
apiVersion: 'homelab.mortenolsen.pro/v1';
kind: 'PostgresDatabase';
name: 'test2';
namespace: 'playground';
foo: 'bar';
foo: 'bar';
{
}

View File

@@ -1,12 +1,12 @@
import { Type } from "@sinclair/typebox";
import { CustomResource, type CustomResourceHandlerOptions } from "../../custom-resource/custom-resource.base.ts";
import { K8sService } from "../../services/k8s.ts";
import { ApiException, type V1Secret } from "@kubernetes/client-node";
import type { CustomResourceRequest } from "../../custom-resource/custom-resource.request.ts";
import { PostgresService } from "../../services/postgres/postgres.service.ts";
import { Type } from '@sinclair/typebox';
import { ApiException, type V1Secret } from '@kubernetes/client-node';
const postgresDatabaseSpecSchema = Type.Object({
});
import { CustomResource, type CustomResourceHandlerOptions } from '../../custom-resource/custom-resource.base.ts';
import { K8sService } from '../../services/k8s.ts';
import type { CustomResourceRequest } from '../../custom-resource/custom-resource.request.ts';
import { PostgresService } from '../../services/postgres/postgres.service.ts';
const postgresDatabaseSpecSchema = Type.Object({});
class PostgresDatabase extends CustomResource<typeof postgresDatabaseSpecSchema> {
constructor() {
@@ -51,7 +51,7 @@ class PostgresDatabase extends CustomResource<typeof postgresDatabaseSpecSchema>
name: Buffer.from(`${metadata.namespace}_${metadata.name}`).toString('base64'),
user: Buffer.from(metadata.name).toString('base64'),
password: Buffer.from(crypto.randomUUID()).toString('base64'),
}
};
const namespace = metadata.namespace ?? 'default';
services.log.debug('Creating secret', { data });
@@ -77,7 +77,7 @@ class PostgresDatabase extends CustomResource<typeof postgresDatabaseSpecSchema>
});
services.log.debug('Secret created', { response });
return response.data!;
}
};
public update = async (options: CustomResourceHandlerOptions<typeof postgresDatabaseSpecSchema>) => {
const { request, services } = options;
@@ -113,7 +113,7 @@ class PostgresDatabase extends CustomResource<typeof postgresDatabaseSpecSchema>
services.log.error('Error updating PostgresRole', { error });
return await status.save();
}
}
};
}
export { PostgresDatabase };

View File

@@ -1,15 +1,18 @@
import { Type } from "@sinclair/typebox";
import { CustomResource, type CustomResourceHandlerOptions } from "../../custom-resource/custom-resource.base.ts";
import { K8sService } from "../../services/k8s.ts";
import { ApiException, type V1Secret } from "@kubernetes/client-node";
import { Type } from '@sinclair/typebox';
import { ApiException, type V1Secret } from '@kubernetes/client-node';
import { CustomResource, type CustomResourceHandlerOptions } from '../../custom-resource/custom-resource.base.ts';
import { K8sService } from '../../services/k8s.ts';
const stringValueSchema = Type.String({
key: Type.String(),
chars: Type.Optional(Type.String()),
length: Type.Optional(Type.Number()),
encoding: Type.Optional(Type.String({
enum: ['utf-8', 'base64', 'base64url', 'hex'],
})),
encoding: Type.Optional(
Type.String({
enum: ['utf-8', 'base64', 'base64url', 'hex'],
}),
),
value: Type.Optional(Type.String()),
});
@@ -71,11 +74,11 @@ class SecretRequest extends CustomResource<typeof secretRequestSpec> {
type: 'Opaque',
data: {
// TODO: generate data from spec
'test': 'test',
test: 'test',
},
},
});
}
};
public update = async (options: CustomResourceHandlerOptions<typeof secretRequestSpec>) => {
const { request } = options;
@@ -88,14 +91,14 @@ class SecretRequest extends CustomResource<typeof secretRequestSpec> {
message: 'Secret created',
});
return await status.save();
} catch (error) {
} catch {
status.setCondition('Ready', {
status: 'False',
reason: 'SecretNotCreated',
message: 'Secret not created',
});
}
}
};
}
export { SecretRequest };

View File

@@ -1,14 +1,15 @@
import { type Static, type TSchema } from "@sinclair/typebox";
import { GROUP } from "../utils/consts.ts";
import type { Services } from "../utils/service.ts";
import { statusSchema } from "./custom-resource.status.ts";
import type { CustomResourceRequest } from "./custom-resource.request.ts";
import { type TSchema } from '@sinclair/typebox';
import { GROUP } from '../utils/consts.ts';
import type { Services } from '../utils/service.ts';
import { statusSchema } from './custom-resource.status.ts';
import type { CustomResourceRequest } from './custom-resource.request.ts';
type CustomResourceHandlerOptions<TSpec extends TSchema> = {
request: CustomResourceRequest<TSpec>;
services: Services;
}
};
type CustomResourceConstructor<TSpec extends TSchema> = {
kind: string;
@@ -17,25 +18,21 @@ type CustomResourceConstructor<TSpec extends TSchema> = {
plural: string;
singular: string;
};
}
};
abstract class CustomResource<
TSpec extends TSchema
> {
abstract class CustomResource<TSpec extends TSchema> {
#options: CustomResourceConstructor<TSpec>;
constructor(options: CustomResourceConstructor<TSpec>) {
this.#options = options;
}
public readonly version = 'v1';
public get name() {
return `${this.#options.names.plural}.${this.group}`;
}
public get version() {
return 'v1';
}
public get group() {
return GROUP;
}
@@ -75,27 +72,28 @@ abstract class CustomResource<
singular: this.#options.names.singular,
},
scope: 'Namespaced',
versions: [{
name: this.version,
served: true,
storage: true,
schema: {
openAPIV3Schema: {
type: 'object',
properties: {
spec: this.spec,
status: statusSchema as any,
}
}
versions: [
{
name: this.version,
served: true,
storage: true,
schema: {
openAPIV3Schema: {
type: 'object',
properties: {
spec: this.spec,
status: statusSchema,
},
},
},
subresources: {
status: {},
},
},
subresources: {
status: {}
}
}]
}
}
}
],
},
};
};
}
export { CustomResource, type CustomResourceConstructor, type CustomResourceHandlerOptions };

View File

@@ -1,13 +1,15 @@
import { ApiException, Watch } from "@kubernetes/client-node";
import { K8sService } from "../services/k8s.ts";
import type { Services } from "../utils/service.ts";
import { type CustomResource } from "./custom-resource.base.ts";
import { CustomResourceRequest } from "./custom-resource.request.ts";
import { ApiException, Watch } from '@kubernetes/client-node';
import { K8sService } from '../services/k8s.ts';
import type { Services } from '../utils/service.ts';
import { type CustomResource } from './custom-resource.base.ts';
import { CustomResourceRequest } from './custom-resource.request.ts';
class CustomResourceRegistry {
#services: Services;
#resources: Set<CustomResource<any>> = new Set();
#watchers: Map<string, AbortController> = new Map();
#resources = new Set<CustomResource<any>>();
#watchers = new Map<string, AbortController>();
constructor(services: Services) {
this.#services = services;
@@ -19,11 +21,11 @@ class CustomResourceRegistry {
public getByKind = (kind: string) => {
return Array.from(this.#resources).find((r) => r.kind === kind);
}
};
public register = (resource: CustomResource<any>) => {
this.#resources.add(resource);
}
};
public unregister = (resource: CustomResource<any>) => {
this.#resources.delete(resource);
@@ -33,7 +35,7 @@ class CustomResourceRegistry {
this.#watchers.delete(kind);
}
});
}
};
public watch = async () => {
const k8sService = this.#services.get(K8sService);
@@ -46,7 +48,7 @@ class CustomResourceRegistry {
const controller = await watcher.watch(path, {}, this.#onResourceEvent, this.#onError);
this.#watchers.set(resource.kind, controller);
}
}
};
#onResourceEvent = async (type: string, obj: any) => {
console.log(type, this.kinds);
@@ -79,12 +81,12 @@ class CustomResourceRegistry {
await handler?.({
request,
services: this.#services,
})
}
});
};
#onError = (error: any) => {
console.error(error);
}
};
public install = async (replace = false) => {
const k8sService = this.#services.get(K8sService);
@@ -107,7 +109,7 @@ class CustomResourceRegistry {
throw error;
}
}
}
};
}
export { CustomResourceRegistry };

View File

@@ -1,9 +1,11 @@
import type { Static, TSchema } from "@sinclair/typebox";
import type { Services } from "../utils/service.ts";
import { K8sService } from "../services/k8s.ts";
import { CustomResourceRegistry } from "./custom-resource.registry.ts";
import { CustomResourceStatus, type CustomResourceStatusType } from "./custom-resource.status.ts";
import { ApiException, PatchStrategy, setHeaderOptions } from "@kubernetes/client-node";
import type { Static, TSchema } from '@sinclair/typebox';
import { ApiException, PatchStrategy, setHeaderOptions } from '@kubernetes/client-node';
import type { Services } from '../utils/service.ts';
import { K8sService } from '../services/k8s.ts';
import { CustomResourceRegistry } from './custom-resource.registry.ts';
import { CustomResourceStatus, type CustomResourceStatusType } from './custom-resource.status.ts';
type CustomResourceRequestOptions = {
type: 'ADDED' | 'DELETED' | 'MODIFIED';
@@ -22,7 +24,7 @@ type CustomResourceRequestMetadata = Record<string, string> & {
generation: number;
};
class CustomResourceRequest<TSpec extends TSchema>{
class CustomResourceRequest<TSpec extends TSchema> {
#options: CustomResourceRequestOptions;
constructor(options: CustomResourceRequestOptions) {
@@ -59,13 +61,14 @@ class CustomResourceRequest<TSpec extends TSchema>{
public isOwnerOf = (manifest: any) => {
const ownerRef = manifest?.metadata?.ownerReferences || [];
return ownerRef.some((ref: any) =>
ref.apiVersion === this.apiVersion &&
ref.kind === this.kind &&
ref.name === this.metadata.name &&
ref.uid === this.metadata.uid
return ownerRef.some(
(ref: any) =>
ref.apiVersion === this.apiVersion &&
ref.kind === this.kind &&
ref.name === this.metadata.name &&
ref.uid === this.metadata.uid,
);
}
};
public setStatus = async (status: CustomResourceStatusType) => {
const { manifest, services } = this.#options;
@@ -80,17 +83,20 @@ class CustomResourceRequest<TSpec extends TSchema>{
const { namespace = 'default', name } = metadata;
const response = await k8sService.customObjectsApi.patchNamespacedCustomObjectStatus({
group: crd.group,
version: crd.version,
namespace,
plural: crd.names.plural,
name,
body: { status },
fieldValidation: 'Strict',
}, setHeaderOptions('Content-Type', PatchStrategy.MergePatch))
const response = await k8sService.customObjectsApi.patchNamespacedCustomObjectStatus(
{
group: crd.group,
version: crd.version,
namespace,
plural: crd.names.plural,
name,
body: { status },
fieldValidation: 'Strict',
},
setHeaderOptions('Content-Type', PatchStrategy.MergePatch),
);
return response;
}
};
public getCurrent = async () => {
const { manifest, services } = this.#options;
@@ -101,19 +107,19 @@ class CustomResourceRequest<TSpec extends TSchema>{
throw new Error(`Custom resource ${manifest.kind} not found`);
}
try {
const resource = await k8sService.customObjectsApi.getNamespacedCustomObject({
group: crd.group,
version: crd.version,
plural: crd.names.plural,
namespace: manifest.metadata.namespace,
name: manifest.metadata.name,
});
return resource as {
apiVersion: string;
kind: string;
metadata: CustomResourceRequestMetadata;
spec: Static<TSpec>;
status: CustomResourceStatusType;
const resource = await k8sService.customObjectsApi.getNamespacedCustomObject({
group: crd.group,
version: crd.version,
plural: crd.names.plural,
namespace: manifest.metadata.namespace,
name: manifest.metadata.name,
});
return resource as {
apiVersion: string;
kind: string;
metadata: CustomResourceRequestMetadata;
spec: Static<TSpec>;
status: CustomResourceStatusType;
};
} catch (error) {
if (error instanceof ApiException && error.code === 404) {
@@ -121,10 +127,10 @@ class CustomResourceRequest<TSpec extends TSchema>{
}
throw error;
}
}
};
public getStatus = async () => {
const resource = await this.getCurrent()
const resource = await this.getCurrent();
if (!resource || !resource.status) {
return new CustomResourceStatus({
status: {
@@ -140,8 +146,7 @@ class CustomResourceRequest<TSpec extends TSchema>{
generation: resource.metadata.generation,
save: this.setStatus,
});
}
};
}
export { CustomResourceRequest };

View File

@@ -1,25 +1,27 @@
import { Type, type Static } from "@sinclair/typebox";
import { Type, type Static } from '@sinclair/typebox';
type CustomResourceStatusType= Static<typeof statusSchema>;
type CustomResourceStatusType = Static<typeof statusSchema>;
const statusSchema = Type.Object({
observedGeneration: Type.Number(),
conditions: Type.Array(Type.Object({
type: Type.String(),
status: Type.String({
enum: ['True', 'False', 'Unknown']
conditions: Type.Array(
Type.Object({
type: Type.String(),
status: Type.String({
enum: ['True', 'False', 'Unknown'],
}),
lastTransitionTime: Type.String(),
reason: Type.String(),
message: Type.String(),
}),
lastTransitionTime: Type.String(),
reason: Type.String(),
message: Type.String(),
})),
),
});
type CustomResourceStatusOptions = {
status?: CustomResourceStatusType;
generation: number;
save: (status: CustomResourceStatusType) => Promise<void>;
}
};
class CustomResourceStatus {
#status: CustomResourceStatusType;
@@ -49,9 +51,12 @@ class CustomResourceStatus {
public getCondition = (type: string) => {
return this.#status.conditions?.find((condition) => condition.type === type)?.status;
}
};
public setCondition = (type: string, condition: Omit<CustomResourceStatusType['conditions'][number], 'type' | 'lastTransitionTime'>) => {
public setCondition = (
type: string,
condition: Omit<CustomResourceStatusType['conditions'][number], 'type' | 'lastTransitionTime'>,
) => {
const currentCondition = this.getCondition(type);
const newCondition = {
...condition,
@@ -59,22 +64,22 @@ class CustomResourceStatus {
lastTransitionTime: new Date().toISOString(),
};
if (currentCondition) {
this.#status.conditions = this.#status.conditions.map((c) => c.type === type ? newCondition : c);
this.#status.conditions = this.#status.conditions.map((c) => (c.type === type ? newCondition : c));
} else {
this.#status.conditions.push(newCondition);
}
}
};
public save = async () => {
await this.#save({
...this.#status,
observedGeneration: this.#generation,
});
}
};
public toJSON = () => {
return this.#status;
}
};
}
export { CustomResourceStatus, statusSchema, type CustomResourceStatusType };

View File

@@ -1,8 +1,10 @@
import knex, { type Knex } from "knex";
import { migrationSource } from "./migrations/migrations.ts";
import { Services } from "../utils/service.ts";
import { PostgresService } from "../services/postgres/postgres.service.ts";
import { ConfigService } from "../services/config/config.ts";
import knex, { type Knex } from 'knex';
import { Services } from '../utils/service.ts';
import { PostgresService } from '../services/postgres/postgres.service.ts';
import { ConfigService } from '../services/config/config.ts';
import { migrationSource } from './migrations/migrations.ts';
const DATABASE_NAME = 'homelab';
@@ -43,15 +45,15 @@ class DatabaseService {
await db.migrate.latest();
return db;
}
};
public getDb = async () => {
if (!this.#knex) {
this.#knex = this.#setup();
}
return this.#knex;
}
};
}
export { tableNames, type Table } from "./migrations/migrations.ts";
export { tableNames, type Table } from './migrations/migrations.ts';
export { DatabaseService };

View File

@@ -1,9 +1,9 @@
import type { Migration } from "./migrations.types.ts";
import type { Migration } from './migrations.types.ts';
const tableNames = {
secrets: 'secrets',
postgresRoles: 'postgres_roles',
}
};
const init: Migration = {
name: 'init',
@@ -27,13 +27,13 @@ const init: Migration = {
await db.schema.dropTable(tableNames.secrets);
await db.schema.dropTable(tableNames.postgresRoles);
},
}
};
type PostgresRoleRow = {
name: string;
namespace: string;
password: string;
}
};
type SecretRow = {
name: string;
@@ -41,11 +41,11 @@ type SecretRow = {
secretName: string;
template: Record<string, unknown>;
data: Record<string, string>;
}
};
type Table = {
secrets: SecretRow;
postgresRoles: PostgresRoleRow;
}
};
export { init, tableNames, type PostgresRoleRow, type SecretRow, type Table };

View File

@@ -1,16 +1,15 @@
import type { Knex } from "knex";
import { init } from "./migrations-001.init.ts";
import type { Migration } from "./migrations.types.ts";
import type { Knex } from 'knex';
const migrations = [
init,
] satisfies Migration[];
import { init } from './migrations-001.init.ts';
import type { Migration } from './migrations.types.ts';
const migrations = [init] satisfies Migration[];
const migrationSource: Knex.MigrationSource<Migration> = {
getMigrations: async () => migrations,
getMigrationName: (migration) => migration.name,
getMigration: async (migration) => migration,
}
};
export { tableNames, type Table } from "./migrations-001.init.ts";
export { tableNames, type Table } from './migrations-001.init.ts';
export { migrationSource };

View File

@@ -1,9 +1,9 @@
import type { Knex } from "knex";
import type { Knex } from 'knex';
type Migration = {
name: string;
up: (db: Knex) => Promise<void>;
down: (db: Knex) => Promise<void>;
}
};
export type { Migration };

View File

@@ -1,19 +1,19 @@
class LogService {
public debug = (message: string, data?: Record<string, unknown>) => {
console.debug(message, data);
}
};
public info = (message: string, data?: Record<string, unknown>) => {
console.info(message, data);
}
};
public warn = (message: string, data?: Record<string, unknown>) => {
console.warn(message, data);
}
};
public error = (message: string, data?: Record<string, unknown>) => {
console.error(message, data);
}
};
}
export { LogService };

View File

@@ -1,7 +1,9 @@
import knex, { type Knex } from "knex";
import type { PostgresDatabase, PostgresRole } from "./postgres.types.ts";
import { Services } from "../../utils/service.ts";
import { ConfigService } from "../config/config.ts";
import knex, { type Knex } from 'knex';
import { Services } from '../../utils/service.ts';
import { ConfigService } from '../config/config.ts';
import type { PostgresDatabase, PostgresRole } from './postgres.types.ts';
class PostgresService {
#db: Knex;
@@ -21,39 +23,24 @@ class PostgresService {
}
public upsertRole = async (role: PostgresRole) => {
const existingRole = await this.#db.raw(
'SELECT 1 FROM pg_roles WHERE rolname = ?',
[role.name]
);
const existingRole = await this.#db.raw('SELECT 1 FROM pg_roles WHERE rolname = ?', [role.name]);
if (existingRole.rows.length === 0) {
await this.#db.raw(
`CREATE ROLE ${role.name} WITH LOGIN PASSWORD '${role.password}'`,
);
await this.#db.raw(`CREATE ROLE ${role.name} WITH LOGIN PASSWORD '${role.password}'`);
} else {
await this.#db.raw(
`ALTER ROLE ${role.name} WITH PASSWORD '${role.password}'`,
);
await this.#db.raw(`ALTER ROLE ${role.name} WITH PASSWORD '${role.password}'`);
}
}
};
public upsertDatabase = async (database: PostgresDatabase) => {
const existingDatabase = await this.#db.raw(
'SELECT * FROM pg_database WHERE datname = ?',
[database.name]
);
const existingDatabase = await this.#db.raw('SELECT * FROM pg_database WHERE datname = ?', [database.name]);
if (existingDatabase.rows.length === 0) {
await this.#db.raw(
`CREATE DATABASE ${database.name} OWNER ${database.owner}`,
);
await this.#db.raw(`CREATE DATABASE ${database.name} OWNER ${database.owner}`);
} else {
await this.#db.raw(
`ALTER DATABASE ${database.name} OWNER TO ${database.owner}`,
);
await this.#db.raw(`ALTER DATABASE ${database.name} OWNER TO ${database.owner}`);
}
}
};
}
export { PostgresService };

View File

@@ -1,2 +1 @@
class SecretsService {
}
class SecretsService {}

View File

@@ -1,9 +1,9 @@
import { LogService } from "../services/log/log.ts";
import { LogService } from '../services/log/log.ts';
type Dependency<T> = new (services: Services) => T;
class Services {
#instances: Map<Dependency<unknown>, unknown> = new Map();
#instances = new Map<Dependency<unknown>, unknown>();
constructor() {
console.log('Constructor', 'bar');
}
@@ -17,7 +17,7 @@ class Services {
this.#instances.set(dependency, new dependency(this));
}
return this.#instances.get(dependency) as T;
}
};
}
export { Services };