mirror of
https://github.com/YuzuZensai/Minikura.git
synced 2026-03-30 18:27:35 +00:00
✨ feat: topology, and improves handling
This commit is contained in:
@@ -4,33 +4,35 @@
|
||||
"type": "module",
|
||||
"exports": "./src/index.ts",
|
||||
"scripts": {
|
||||
"dev": "bun --watch src/index.ts",
|
||||
"build": "bun build src/index.ts --target bun --outdir ./dist",
|
||||
"start": "NODE_ENV=production bun dist/index.js",
|
||||
"dev": "tsx watch src/index.ts",
|
||||
"dev:bun": "bun --watch src/index.ts",
|
||||
"build": "tsc",
|
||||
"start": "NODE_ENV=production node dist/index.js",
|
||||
"test": "bun test",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"lint": "biome lint .",
|
||||
"format": "biome format --write ."
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bcryptjs": "^3.0.0",
|
||||
"@types/bun": "^1.3.6"
|
||||
"@types/bun": "^1.3.6",
|
||||
"@types/node": "^25.0.9",
|
||||
"tsx": "^4.19.2"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"typescript": "^5.0.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@elysiajs/cors": "1.1.1",
|
||||
"@elysiajs/swagger": "1.1.3",
|
||||
"@elysiajs/node": "^1.4.5",
|
||||
"@kubernetes/client-node": "^1.4.0",
|
||||
"@minikura/api": "workspace:*",
|
||||
"@minikura/db": "workspace:*",
|
||||
"@sinclair/typebox": "^0.34.47",
|
||||
"@minikura/shared": "workspace:*",
|
||||
"@types/ws": "^8.18.1",
|
||||
"argon2": "^0.44.0",
|
||||
"bcryptjs": "^3.0.3",
|
||||
"better-auth": "^1.4.13",
|
||||
"dotenv": "^17.2.3",
|
||||
"elysia": "^1.4.22",
|
||||
"pino": "^10.3.1",
|
||||
"pino-http": "^11.0.0",
|
||||
"pino-pretty": "^13.1.3",
|
||||
"undici": "^7.18.2",
|
||||
"ws": "^8.19.0",
|
||||
"yaml": "^2.8.2",
|
||||
|
||||
@@ -12,9 +12,11 @@ const userRepo = new PrismaUserRepository();
|
||||
const serverRepo = new PrismaServerRepository();
|
||||
const reverseProxyRepo = new PrismaReverseProxyRepository();
|
||||
const webSocketService = new WebSocketService();
|
||||
const k8sService = new K8sService();
|
||||
|
||||
// Application layer
|
||||
export const userService = new UserService(userRepo);
|
||||
export const serverService = new ServerService(serverRepo, K8sService.getInstance());
|
||||
export const serverService = new ServerService(serverRepo, k8sService);
|
||||
export const reverseProxyService = new ReverseProxyService(reverseProxyRepo);
|
||||
export const wsService = webSocketService;
|
||||
export { k8sService };
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import type * as k8s from "@kubernetes/client-node";
|
||||
import type { CustomResourceSummary } from "@minikura/api";
|
||||
|
||||
export interface IK8sService {
|
||||
// Initialization
|
||||
isInitialized(): boolean;
|
||||
getConnectionInfo(): {
|
||||
initialized: boolean;
|
||||
currentContext?: string;
|
||||
cluster?: string;
|
||||
namespace: string;
|
||||
};
|
||||
|
||||
// Pods
|
||||
getPods(): Promise<any[]>;
|
||||
getPodsByLabel(labelSelector: string): Promise<any[]>;
|
||||
getPodInfo(podName: string): Promise<any>;
|
||||
getPodLogs(
|
||||
podName: string,
|
||||
options?: {
|
||||
container?: string;
|
||||
tailLines?: number;
|
||||
timestamps?: boolean;
|
||||
sinceSeconds?: number;
|
||||
}
|
||||
): Promise<string>;
|
||||
getPodMetrics(namespace?: string): Promise<any>;
|
||||
|
||||
// Workloads
|
||||
getDeployments(): Promise<any[]>;
|
||||
getStatefulSets(): Promise<any[]>;
|
||||
|
||||
// Network
|
||||
getServices(): Promise<any[]>;
|
||||
getIngresses(): Promise<any[]>;
|
||||
getServiceInfo(serviceName: string): Promise<any>;
|
||||
getServerConnectionInfo(serviceName: string): Promise<any>;
|
||||
|
||||
// Configuration
|
||||
getConfigMaps(): Promise<any[]>;
|
||||
|
||||
// Custom Resources
|
||||
getCustomResources(
|
||||
group: string,
|
||||
version: string,
|
||||
plural: string
|
||||
): Promise<CustomResourceSummary[]>;
|
||||
getMinecraftServers(): Promise<CustomResourceSummary[]>;
|
||||
getReverseProxyServers(): Promise<CustomResourceSummary[]>;
|
||||
|
||||
// Cluster
|
||||
getNodes(): Promise<any[]>;
|
||||
getNodeMetrics(): Promise<any>;
|
||||
|
||||
// Low-level access
|
||||
getKubeConfig(): k8s.KubeConfig;
|
||||
getCoreApi(): k8s.CoreV1Api;
|
||||
getNamespace(): string;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import type { EnvVariable, ReverseProxyWithEnvVars } from "@minikura/db";
|
||||
import type {
|
||||
ReverseProxyCreateInput,
|
||||
ReverseProxyUpdateInput,
|
||||
} from "../../domain/repositories/reverse-proxy.repository";
|
||||
|
||||
export interface IReverseProxyService {
|
||||
getAllReverseProxies(omitSensitive?: boolean): Promise<ReverseProxyWithEnvVars[]>;
|
||||
getReverseProxyById(id: string, omitSensitive?: boolean): Promise<ReverseProxyWithEnvVars>;
|
||||
createReverseProxy(input: ReverseProxyCreateInput): Promise<ReverseProxyWithEnvVars>;
|
||||
updateReverseProxy(id: string, input: ReverseProxyUpdateInput): Promise<ReverseProxyWithEnvVars>;
|
||||
deleteReverseProxy(id: string): Promise<void>;
|
||||
setEnvVariable(proxyId: string, key: string, value: string): Promise<void>;
|
||||
getEnvVariables(proxyId: string): Promise<EnvVariable[]>;
|
||||
deleteEnvVariable(proxyId: string, key: string): Promise<void>;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import type { EnvVariable, ServerWithEnvVars } from "@minikura/db";
|
||||
import type {
|
||||
ServerCreateInput,
|
||||
ServerUpdateInput,
|
||||
} from "../../domain/repositories/server.repository";
|
||||
|
||||
export interface IServerService {
|
||||
getAllServers(omitSensitive?: boolean): Promise<ServerWithEnvVars[]>;
|
||||
getServerById(id: string, omitSensitive?: boolean): Promise<ServerWithEnvVars>;
|
||||
createServer(input: ServerCreateInput): Promise<ServerWithEnvVars>;
|
||||
updateServer(id: string, input: ServerUpdateInput): Promise<ServerWithEnvVars>;
|
||||
deleteServer(id: string): Promise<void>;
|
||||
setEnvVariable(serverId: string, key: string, value: string): Promise<void>;
|
||||
getEnvVariables(serverId: string): Promise<EnvVariable[]>;
|
||||
deleteEnvVariable(serverId: string, key: string): Promise<void>;
|
||||
getConnectionInfo(serverId: string): Promise<any>;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import type { UpdateSuspensionInput, UpdateUserInput, User } from "@minikura/db";
|
||||
|
||||
export interface IUserService {
|
||||
getUserById(id: string): Promise<User>;
|
||||
getUserByEmail(email: string): Promise<User | null>;
|
||||
getAllUsers(): Promise<User[]>;
|
||||
updateUser(id: string, input: UpdateUserInput): Promise<User>;
|
||||
updateSuspension(id: string, input: UpdateSuspensionInput): Promise<User>;
|
||||
suspendUser(id: string, suspendedUntil?: Date | null): Promise<User>;
|
||||
unsuspendUser(id: string): Promise<User>;
|
||||
deleteUser(requestingUserId: string, targetUserId: string): Promise<void>;
|
||||
}
|
||||
82
apps/backend/src/application/services/base-crud.service.ts
Normal file
82
apps/backend/src/application/services/base-crud.service.ts
Normal file
@@ -0,0 +1,82 @@
|
||||
import type { EnvVariable } from "@minikura/db";
|
||||
import { ConflictError, NotFoundError } from "../../domain/errors/base.error";
|
||||
import { eventBus } from "../../infrastructure/event-bus";
|
||||
|
||||
export abstract class BaseCrudService<
|
||||
TEntity,
|
||||
TCreateInput,
|
||||
TUpdateInput,
|
||||
TRepository extends {
|
||||
findAll(omitSensitive?: boolean): Promise<TEntity[]>;
|
||||
findById(id: string, omitSensitive?: boolean): Promise<TEntity | null>;
|
||||
exists(id: string): Promise<boolean>;
|
||||
create(input: TCreateInput): Promise<TEntity>;
|
||||
update(id: string, input: TUpdateInput): Promise<TEntity>;
|
||||
delete(id: string): Promise<void>;
|
||||
setEnvVariable(entityId: string, key: string, value: string): Promise<void>;
|
||||
getEnvVariables(entityId: string): Promise<EnvVariable[]>;
|
||||
deleteEnvVariable(entityId: string, key: string): Promise<void>;
|
||||
},
|
||||
TEvents extends {
|
||||
created: new (id: string, type: any, input: TCreateInput) => any;
|
||||
updated: new (id: string, input: TUpdateInput) => any;
|
||||
deleted: new (id: string) => any;
|
||||
},
|
||||
> {
|
||||
constructor(
|
||||
protected repository: TRepository,
|
||||
protected events: TEvents,
|
||||
protected entityName: string
|
||||
) {}
|
||||
|
||||
protected abstract getEntityType(input: TCreateInput): any;
|
||||
protected abstract getInputId(input: TCreateInput): string;
|
||||
|
||||
async getAll(omitSensitive = false): Promise<TEntity[]> {
|
||||
return this.repository.findAll(omitSensitive);
|
||||
}
|
||||
|
||||
async getById(id: string, omitSensitive = false): Promise<TEntity> {
|
||||
const entity = await this.repository.findById(id, omitSensitive);
|
||||
if (!entity) {
|
||||
throw new NotFoundError(this.entityName, id);
|
||||
}
|
||||
return entity;
|
||||
}
|
||||
|
||||
async create(input: TCreateInput): Promise<TEntity> {
|
||||
const id = this.getInputId(input);
|
||||
const existing = await this.repository.exists(id);
|
||||
if (existing) {
|
||||
throw new ConflictError(this.entityName, id);
|
||||
}
|
||||
|
||||
const entity = await this.repository.create(input);
|
||||
const type = this.getEntityType(input);
|
||||
await eventBus.publish(new this.events.created(id, type, input));
|
||||
return entity;
|
||||
}
|
||||
|
||||
async update(id: string, input: TUpdateInput): Promise<TEntity> {
|
||||
const entity = await this.repository.update(id, input);
|
||||
await eventBus.publish(new this.events.updated(id, input));
|
||||
return entity;
|
||||
}
|
||||
|
||||
async delete(id: string): Promise<void> {
|
||||
await this.repository.delete(id);
|
||||
await eventBus.publish(new this.events.deleted(id));
|
||||
}
|
||||
|
||||
async setEnvVariable(entityId: string, key: string, value: string): Promise<void> {
|
||||
await this.repository.setEnvVariable(entityId, key, value);
|
||||
}
|
||||
|
||||
async getEnvVariables(entityId: string): Promise<EnvVariable[]> {
|
||||
return this.repository.getEnvVariables(entityId);
|
||||
}
|
||||
|
||||
async deleteEnvVariable(entityId: string, key: string): Promise<void> {
|
||||
await this.repository.deleteEnvVariable(entityId, key);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
import type { EnvVariable, ReverseProxyWithEnvVars } from "@minikura/db";
|
||||
import { ConflictError, NotFoundError } from "../../domain/errors/base.error";
|
||||
import type { ReverseProxyWithEnvVars } from "@minikura/db";
|
||||
import {
|
||||
ReverseProxyCreatedEvent,
|
||||
ReverseProxyDeletedEvent,
|
||||
@@ -10,71 +9,60 @@ import type {
|
||||
ReverseProxyRepository,
|
||||
ReverseProxyUpdateInput,
|
||||
} from "../../domain/repositories/reverse-proxy.repository";
|
||||
import { eventBus } from "../../infrastructure/event-bus";
|
||||
import type { IReverseProxyService } from "../interfaces/reverse-proxy.service.interface";
|
||||
import { BaseCrudService } from "./base-crud.service";
|
||||
|
||||
export class ReverseProxyService {
|
||||
constructor(private reverseProxyRepo: ReverseProxyRepository) {}
|
||||
|
||||
async getAllReverseProxies(
|
||||
omitSensitive = false,
|
||||
): Promise<ReverseProxyWithEnvVars[]> {
|
||||
return this.reverseProxyRepo.findAll(omitSensitive);
|
||||
}
|
||||
|
||||
async getReverseProxyById(
|
||||
id: string,
|
||||
omitSensitive = false,
|
||||
): Promise<ReverseProxyWithEnvVars> {
|
||||
const proxy = await this.reverseProxyRepo.findById(id, omitSensitive);
|
||||
if (!proxy) {
|
||||
throw new NotFoundError("ReverseProxyServer", id);
|
||||
export class ReverseProxyService
|
||||
extends BaseCrudService<
|
||||
ReverseProxyWithEnvVars,
|
||||
ReverseProxyCreateInput,
|
||||
ReverseProxyUpdateInput,
|
||||
ReverseProxyRepository,
|
||||
{
|
||||
created: typeof ReverseProxyCreatedEvent;
|
||||
updated: typeof ReverseProxyUpdatedEvent;
|
||||
deleted: typeof ReverseProxyDeletedEvent;
|
||||
}
|
||||
return proxy;
|
||||
}
|
||||
|
||||
async createReverseProxy(
|
||||
input: ReverseProxyCreateInput,
|
||||
): Promise<ReverseProxyWithEnvVars> {
|
||||
const id = typeof input.id === "string" ? input.id : String(input.id);
|
||||
const existing = await this.reverseProxyRepo.exists(id);
|
||||
if (existing) {
|
||||
throw new ConflictError("ReverseProxyServer", id);
|
||||
}
|
||||
|
||||
const proxy = await this.reverseProxyRepo.create(input);
|
||||
await eventBus.publish(
|
||||
new ReverseProxyCreatedEvent(proxy.id, proxy.type, input),
|
||||
>
|
||||
implements IReverseProxyService
|
||||
{
|
||||
constructor(reverseProxyRepo: ReverseProxyRepository) {
|
||||
super(
|
||||
reverseProxyRepo,
|
||||
{
|
||||
created: ReverseProxyCreatedEvent,
|
||||
updated: ReverseProxyUpdatedEvent,
|
||||
deleted: ReverseProxyDeletedEvent,
|
||||
},
|
||||
"ReverseProxyServer"
|
||||
);
|
||||
return proxy;
|
||||
}
|
||||
|
||||
async updateReverseProxy(
|
||||
id: string,
|
||||
input: ReverseProxyUpdateInput,
|
||||
): Promise<ReverseProxyWithEnvVars> {
|
||||
const proxy = await this.reverseProxyRepo.update(id, input);
|
||||
await eventBus.publish(new ReverseProxyUpdatedEvent(id, input));
|
||||
return proxy;
|
||||
protected getEntityType(input: ReverseProxyCreateInput) {
|
||||
return input.type || "VELOCITY";
|
||||
}
|
||||
|
||||
async deleteReverseProxy(id: string): Promise<void> {
|
||||
await this.reverseProxyRepo.delete(id);
|
||||
await eventBus.publish(new ReverseProxyDeletedEvent(id));
|
||||
protected getInputId(input: ReverseProxyCreateInput): string {
|
||||
return typeof input.id === "string" ? input.id : String(input.id);
|
||||
}
|
||||
|
||||
async setEnvVariable(
|
||||
proxyId: string,
|
||||
key: string,
|
||||
value: string,
|
||||
): Promise<void> {
|
||||
await this.reverseProxyRepo.setEnvVariable(proxyId, key, value);
|
||||
getAllReverseProxies(omitSensitive = false) {
|
||||
return this.getAll(omitSensitive);
|
||||
}
|
||||
|
||||
async getEnvVariables(proxyId: string): Promise<EnvVariable[]> {
|
||||
return this.reverseProxyRepo.getEnvVariables(proxyId);
|
||||
getReverseProxyById(id: string, omitSensitive = false) {
|
||||
return this.getById(id, omitSensitive);
|
||||
}
|
||||
|
||||
async deleteEnvVariable(proxyId: string, key: string): Promise<void> {
|
||||
await this.reverseProxyRepo.deleteEnvVariable(proxyId, key);
|
||||
createReverseProxy(input: ReverseProxyCreateInput) {
|
||||
return this.create(input);
|
||||
}
|
||||
|
||||
updateReverseProxy(id: string, input: ReverseProxyUpdateInput) {
|
||||
return this.update(id, input);
|
||||
}
|
||||
|
||||
deleteReverseProxy(id: string) {
|
||||
return this.delete(id);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import type { EnvVariable, ServerWithEnvVars } from "@minikura/db";
|
||||
import { ConflictError, NotFoundError } from "../../domain/errors/base.error";
|
||||
import type { ServerWithEnvVars } from "@minikura/db";
|
||||
import {
|
||||
ServerCreatedEvent,
|
||||
ServerDeletedEvent,
|
||||
@@ -10,71 +9,65 @@ import type {
|
||||
ServerRepository,
|
||||
ServerUpdateInput,
|
||||
} from "../../domain/repositories/server.repository";
|
||||
import { eventBus } from "../../infrastructure/event-bus";
|
||||
import type { K8sService } from "../../services/k8s";
|
||||
import type { IServerService } from "../interfaces/server.service.interface";
|
||||
import { BaseCrudService } from "./base-crud.service";
|
||||
|
||||
export class ServerService {
|
||||
export class ServerService
|
||||
extends BaseCrudService<
|
||||
ServerWithEnvVars,
|
||||
ServerCreateInput,
|
||||
ServerUpdateInput,
|
||||
ServerRepository,
|
||||
{
|
||||
created: typeof ServerCreatedEvent;
|
||||
updated: typeof ServerUpdatedEvent;
|
||||
deleted: typeof ServerDeletedEvent;
|
||||
}
|
||||
>
|
||||
implements IServerService
|
||||
{
|
||||
constructor(
|
||||
private serverRepo: ServerRepository,
|
||||
private k8sService: K8sService,
|
||||
) {}
|
||||
|
||||
async getAllServers(omitSensitive = false): Promise<ServerWithEnvVars[]> {
|
||||
return this.serverRepo.findAll(omitSensitive);
|
||||
}
|
||||
|
||||
async getServerById(
|
||||
id: string,
|
||||
omitSensitive = false,
|
||||
): Promise<ServerWithEnvVars> {
|
||||
const server = await this.serverRepo.findById(id, omitSensitive);
|
||||
if (!server) {
|
||||
throw new NotFoundError("Server", id);
|
||||
}
|
||||
return server;
|
||||
}
|
||||
|
||||
async createServer(input: ServerCreateInput): Promise<ServerWithEnvVars> {
|
||||
const existing = await this.serverRepo.exists(input.id);
|
||||
if (existing) {
|
||||
throw new ConflictError("Server", input.id);
|
||||
}
|
||||
|
||||
const server = await this.serverRepo.create(input);
|
||||
await eventBus.publish(
|
||||
new ServerCreatedEvent(server.id, server.type, input),
|
||||
serverRepo: ServerRepository,
|
||||
private k8sService: K8sService
|
||||
) {
|
||||
super(
|
||||
serverRepo,
|
||||
{
|
||||
created: ServerCreatedEvent,
|
||||
updated: ServerUpdatedEvent,
|
||||
deleted: ServerDeletedEvent,
|
||||
},
|
||||
"Server"
|
||||
);
|
||||
return server;
|
||||
}
|
||||
|
||||
async updateServer(
|
||||
id: string,
|
||||
input: ServerUpdateInput,
|
||||
): Promise<ServerWithEnvVars> {
|
||||
const server = await this.serverRepo.update(id, input);
|
||||
await eventBus.publish(new ServerUpdatedEvent(id, input));
|
||||
return server;
|
||||
protected getEntityType(input: ServerCreateInput) {
|
||||
return input.type;
|
||||
}
|
||||
|
||||
async deleteServer(id: string): Promise<void> {
|
||||
await this.serverRepo.delete(id);
|
||||
await eventBus.publish(new ServerDeletedEvent(id));
|
||||
protected getInputId(input: ServerCreateInput): string {
|
||||
return input.id;
|
||||
}
|
||||
|
||||
async setEnvVariable(
|
||||
serverId: string,
|
||||
key: string,
|
||||
value: string,
|
||||
): Promise<void> {
|
||||
await this.serverRepo.setEnvVariable(serverId, key, value);
|
||||
getAllServers(omitSensitive = false) {
|
||||
return this.getAll(omitSensitive);
|
||||
}
|
||||
|
||||
async getEnvVariables(serverId: string): Promise<EnvVariable[]> {
|
||||
return this.serverRepo.getEnvVariables(serverId);
|
||||
getServerById(id: string, omitSensitive = false) {
|
||||
return this.getById(id, omitSensitive);
|
||||
}
|
||||
|
||||
async deleteEnvVariable(serverId: string, key: string): Promise<void> {
|
||||
await this.serverRepo.deleteEnvVariable(serverId, key);
|
||||
createServer(input: ServerCreateInput) {
|
||||
return this.create(input);
|
||||
}
|
||||
|
||||
updateServer(id: string, input: ServerUpdateInput) {
|
||||
return this.update(id, input);
|
||||
}
|
||||
|
||||
deleteServer(id: string) {
|
||||
return this.delete(id);
|
||||
}
|
||||
|
||||
async getConnectionInfo(serverId: string) {
|
||||
|
||||
@@ -6,8 +6,9 @@ import {
|
||||
} from "../../domain/events/server-lifecycle.events";
|
||||
import type { UserRepository } from "../../domain/repositories/user.repository";
|
||||
import { eventBus } from "../../infrastructure/event-bus";
|
||||
import type { IUserService } from "../interfaces/user.service.interface";
|
||||
|
||||
export class UserService {
|
||||
export class UserService implements IUserService {
|
||||
constructor(private userRepo: UserRepository) {}
|
||||
|
||||
async getUserById(id: string): Promise<User> {
|
||||
|
||||
@@ -32,9 +32,7 @@ export class ConflictError extends DomainError {
|
||||
readonly statusCode = 409;
|
||||
|
||||
constructor(resource: string, identifier?: string) {
|
||||
super(
|
||||
identifier ? `${resource} already exists: ${identifier}` : `${resource} already exists`
|
||||
);
|
||||
super(identifier ? `${resource} already exists: ${identifier}` : `${resource} already exists`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -59,17 +57,9 @@ export class ForbiddenError extends DomainError {
|
||||
export class ValidationError extends DomainError {
|
||||
readonly code = "VALIDATION_ERROR";
|
||||
readonly statusCode = 400;
|
||||
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
export class BusinessRuleError extends DomainError {
|
||||
readonly code = "BUSINESS_RULE_VIOLATION";
|
||||
readonly statusCode = 422;
|
||||
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { DomainEvent } from "./domain-event";
|
||||
import type { ReverseProxyType } from "../entities/enums";
|
||||
import type { ReverseProxyCreateInput, ReverseProxyUpdateInput } from "../repositories/reverse-proxy.repository";
|
||||
import type {
|
||||
ReverseProxyCreateInput,
|
||||
ReverseProxyUpdateInput,
|
||||
} from "../repositories/reverse-proxy.repository";
|
||||
import { DomainEvent } from "./domain-event";
|
||||
|
||||
export class ReverseProxyCreatedEvent extends DomainEvent {
|
||||
constructor(
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { EnvVariable, Server, ServerWithEnvVars } from "@minikura/db";
|
||||
import type { EnvVariable, ServerWithEnvVars } from "@minikura/db";
|
||||
import type { z } from "zod";
|
||||
import type { createServerSchema, updateServerSchema } from "../../schemas/server.schema";
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ export class ServerConfig {
|
||||
}
|
||||
|
||||
getJvmArgs(): string {
|
||||
const args: string[] = ["-Xmx" + this.memory + "M"];
|
||||
const args: string[] = [`-Xmx${this.memory}M`];
|
||||
|
||||
if (this.jvmOpts) {
|
||||
args.push(this.jvmOpts);
|
||||
|
||||
@@ -3,12 +3,14 @@ import { dotenvLoad } from "dotenv-mono";
|
||||
dotenvLoad();
|
||||
|
||||
import { Elysia } from "elysia";
|
||||
import { auth } from "./lib/auth";
|
||||
import { authPlugin } from "./lib/auth-plugin";
|
||||
import { errorHandler } from "./lib/error-handler";
|
||||
import { node } from "@elysiajs/node";
|
||||
import { logger } from "./infrastructure/logger";
|
||||
import { auth } from "./middleware/auth";
|
||||
import { authPlugin } from "./middleware/auth-plugin";
|
||||
import { errorHandler } from "./middleware/error-handler";
|
||||
import { bootstrapRoutes } from "./routes/bootstrap";
|
||||
import { k8sRoutes } from "./routes/k8s";
|
||||
import { reverseProxyRoutes } from "./routes/reverse-proxy.routes";
|
||||
import { reverseProxyRoutes } from "./routes/reverse-proxy";
|
||||
import { serverRoutes } from "./routes/servers";
|
||||
import { terminalRoutes } from "./routes/terminal";
|
||||
import { userRoutes } from "./routes/users";
|
||||
@@ -16,7 +18,7 @@ import { userRoutes } from "./routes/users";
|
||||
// Register event handlers
|
||||
import "./infrastructure/event-handlers";
|
||||
|
||||
const app = new Elysia()
|
||||
const app = new Elysia({ adapter: node() })
|
||||
.use(errorHandler)
|
||||
.onRequest(({ set }) => {
|
||||
const origin = process.env.WEB_URL || "http://localhost:3001";
|
||||
@@ -37,5 +39,5 @@ const app = new Elysia()
|
||||
export type App = typeof app;
|
||||
|
||||
app.listen(3000, () => {
|
||||
console.log("Server running on http://localhost:3000");
|
||||
logger.info({ port: 3000, url: "http://localhost:3000" }, "Backend API server started");
|
||||
});
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { DomainEvent } from "../domain/events/domain-event";
|
||||
import { logger } from "./logger";
|
||||
|
||||
type EventHandler<T extends DomainEvent = DomainEvent> = (event: T) => void | Promise<void>;
|
||||
|
||||
@@ -14,7 +15,7 @@ export class EventBus {
|
||||
if (!this.handlers.has(eventName)) {
|
||||
this.handlers.set(eventName, new Set());
|
||||
}
|
||||
this.handlers.get(eventName)!.add(handler as EventHandler);
|
||||
this.handlers.get(eventName)?.add(handler as EventHandler);
|
||||
return () => {
|
||||
this.handlers.get(eventName)?.delete(handler as EventHandler);
|
||||
};
|
||||
@@ -28,7 +29,7 @@ export class EventBus {
|
||||
try {
|
||||
await handler(event);
|
||||
} catch (error) {
|
||||
console.error(`[EventBus] Error in handler for ${eventName}:`, error);
|
||||
logger.error({ err: error, eventName }, "Error executing event handler");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import "./server-event.handler";
|
||||
import "./user-event.handler";
|
||||
|
||||
console.log("[EventBus] All event handlers registered");
|
||||
import { logger } from "../logger";
|
||||
|
||||
logger.debug("All domain event handlers registered");
|
||||
|
||||
@@ -1,22 +1,23 @@
|
||||
import { wsService } from "../../application/di-container";
|
||||
import {
|
||||
ServerCreatedEvent,
|
||||
ServerDeletedEvent,
|
||||
ServerUpdatedEvent,
|
||||
} from "../../domain/events/server-lifecycle.events";
|
||||
import { eventBus } from "../event-bus";
|
||||
import { wsService } from "../../application/di-container";
|
||||
import { logger } from "../logger";
|
||||
|
||||
eventBus.subscribe(ServerCreatedEvent, async (event) => {
|
||||
console.log(`[Event] Server created: ${event.serverId} (${event.serverType})`);
|
||||
logger.info({ serverId: event.serverId, serverType: event.serverType }, "Server created event");
|
||||
wsService.broadcast("create", event.serverType, event.serverId);
|
||||
});
|
||||
|
||||
eventBus.subscribe(ServerUpdatedEvent, async (event) => {
|
||||
console.log(`[Event] Server updated: ${event.serverId}`);
|
||||
logger.info({ serverId: event.serverId }, "Server updated event");
|
||||
wsService.broadcast("update", "server", event.serverId);
|
||||
});
|
||||
|
||||
eventBus.subscribe(ServerDeletedEvent, async (event) => {
|
||||
console.log(`[Event] Server deleted: ${event.serverId}`);
|
||||
logger.info({ serverId: event.serverId }, "Server deleted event");
|
||||
wsService.broadcast("delete", "server", event.serverId);
|
||||
});
|
||||
|
||||
@@ -3,17 +3,19 @@ import {
|
||||
UserUnsuspendedEvent,
|
||||
} from "../../domain/events/server-lifecycle.events";
|
||||
import { eventBus } from "../event-bus";
|
||||
import { logger } from "../logger";
|
||||
|
||||
eventBus.subscribe(UserSuspendedEvent, async (event) => {
|
||||
if (event.suspendedUntil) {
|
||||
console.log(
|
||||
`[Event] User suspended: ${event.userId} until ${event.suspendedUntil.toISOString()}`
|
||||
logger.warn(
|
||||
{ userId: event.userId, suspendedUntil: event.suspendedUntil.toISOString() },
|
||||
"User suspended with expiry"
|
||||
);
|
||||
} else {
|
||||
console.log(`[Event] User suspended: ${event.userId} indefinitely`);
|
||||
logger.warn({ userId: event.userId }, "User suspended indefinitely");
|
||||
}
|
||||
});
|
||||
|
||||
eventBus.subscribe(UserUnsuspendedEvent, async (event) => {
|
||||
console.log(`[Event] User unsuspended: ${event.userId}`);
|
||||
logger.info({ userId: event.userId }, "User unsuspended");
|
||||
});
|
||||
|
||||
5
apps/backend/src/infrastructure/logger.ts
Normal file
5
apps/backend/src/infrastructure/logger.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
import { createLogger } from "@minikura/shared";
|
||||
|
||||
export { createLogger };
|
||||
|
||||
export const logger = createLogger("backend-api");
|
||||
@@ -1,5 +1,4 @@
|
||||
import { prisma, type UpdateSuspensionInput, type UpdateUserInput, type User } from "@minikura/db";
|
||||
import { UserRole } from "../../../domain/entities/enums";
|
||||
import type { UserRepository } from "../../../domain/repositories/user.repository";
|
||||
|
||||
export class PrismaUserRepository implements UserRepository {
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
export const getErrorMessage = (error: unknown): string => {
|
||||
if (error instanceof Error) {
|
||||
return error.message;
|
||||
}
|
||||
if (typeof error === "string") {
|
||||
return error;
|
||||
}
|
||||
return "Unknown error";
|
||||
};
|
||||
@@ -1,52 +0,0 @@
|
||||
import * as https from "node:https";
|
||||
import * as k8s from "@kubernetes/client-node";
|
||||
import { Agent as UndiciAgent } from "undici";
|
||||
|
||||
let clientCert: string | undefined;
|
||||
let clientKey: string | undefined;
|
||||
let caCert: string | undefined;
|
||||
|
||||
try {
|
||||
const kc = new k8s.KubeConfig();
|
||||
kc.loadFromDefault();
|
||||
const user = kc.getCurrentUser();
|
||||
const cluster = kc.getCurrentCluster();
|
||||
|
||||
if (user?.certData) {
|
||||
clientCert = Buffer.from(user.certData, "base64").toString();
|
||||
}
|
||||
if (user?.keyData) {
|
||||
clientKey = Buffer.from(user.keyData, "base64").toString();
|
||||
}
|
||||
if (cluster?.caData) {
|
||||
caCert = Buffer.from(cluster.caData, "base64").toString();
|
||||
}
|
||||
|
||||
if (clientCert && clientKey) {
|
||||
const OriginalAgent = https.Agent;
|
||||
type UndiciOptions = ConstructorParameters<typeof UndiciAgent>[0];
|
||||
const httpsModule = https as typeof https & { Agent: typeof https.Agent };
|
||||
|
||||
httpsModule.Agent = class PatchedAgent extends OriginalAgent {
|
||||
constructor(options?: https.AgentOptions) {
|
||||
super(options);
|
||||
|
||||
const undiciOptions: UndiciOptions = {
|
||||
connect: {
|
||||
cert: clientCert,
|
||||
key: clientKey,
|
||||
ca: caCert,
|
||||
rejectUnauthorized: process.env.KUBERNETES_SKIP_TLS_VERIFY !== "true",
|
||||
},
|
||||
};
|
||||
|
||||
const patched = this as unknown as { _undiciAgent?: UndiciAgent };
|
||||
patched._undiciAgent = new UndiciAgent(undiciOptions);
|
||||
}
|
||||
};
|
||||
|
||||
console.log("Patched https.Agent to use undici with client certificates");
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn("Failed to patch https.Agent for Kubernetes:", err);
|
||||
}
|
||||
@@ -1,107 +0,0 @@
|
||||
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { KubeConfig } from "@kubernetes/client-node";
|
||||
import { spawnSync } from "bun";
|
||||
import YAML from "yaml";
|
||||
|
||||
type KubeConfigDoc = {
|
||||
users?: Array<{ name: string; user: { token?: string } }>;
|
||||
contexts?: Array<{
|
||||
name: string;
|
||||
context: { cluster: string; user: string; namespace?: string };
|
||||
}>;
|
||||
clusters?: Array<{ name: string }>;
|
||||
};
|
||||
|
||||
const SA_NAME = process.env.K8S_SA_NAME || "minikura-backend";
|
||||
const NAMESPACE = process.env.KUBERNETES_NAMESPACE || "minikura";
|
||||
const TOKEN_DURATION_HOURS = Number(process.env.K8S_TOKEN_DURATION_HOURS || 24);
|
||||
const TOKEN_REFRESH_MIN = Number(process.env.K8S_TOKEN_REFRESH_MIN || 60);
|
||||
|
||||
function kubeconfigPath(): string {
|
||||
return process.env.KUBECONFIG || `${process.env.HOME || process.env.USERPROFILE}/.kube/config`;
|
||||
}
|
||||
|
||||
function refreshSaToken(): void {
|
||||
const duration = `${TOKEN_DURATION_HOURS}h`;
|
||||
const args = ["kubectl", "-n", NAMESPACE, "create", "token", SA_NAME, "--duration", duration];
|
||||
|
||||
if (process.env.KUBERNETES_SKIP_TLS_VERIFY === "true") {
|
||||
args.push("--insecure-skip-tls-verify");
|
||||
}
|
||||
|
||||
const proc = spawnSync(args);
|
||||
|
||||
if (proc.exitCode !== 0) {
|
||||
console.error("[kube-auth] kubectl create token failed:", proc.stderr.toString());
|
||||
return;
|
||||
}
|
||||
|
||||
const token = proc.stdout.toString().trim();
|
||||
const kcPath = kubeconfigPath();
|
||||
|
||||
if (!existsSync(kcPath)) {
|
||||
console.error("[kube-auth] kubeconfig not found at:", kcPath);
|
||||
return;
|
||||
}
|
||||
|
||||
const doc = YAML.parse(readFileSync(kcPath, "utf8")) as KubeConfigDoc;
|
||||
|
||||
let user = doc.users?.find((existingUser) => existingUser.name === SA_NAME);
|
||||
if (!user) {
|
||||
user = { name: SA_NAME, user: {} };
|
||||
if (!doc.users) doc.users = [];
|
||||
doc.users.push(user);
|
||||
}
|
||||
user.user = { token };
|
||||
|
||||
let ctx = doc.contexts?.find((context) => context.name === "bun-local");
|
||||
if (!ctx) {
|
||||
const clusterName = doc.clusters?.[0]?.name || "default";
|
||||
ctx = {
|
||||
name: "bun-local",
|
||||
context: {
|
||||
cluster: clusterName,
|
||||
user: SA_NAME,
|
||||
namespace: NAMESPACE,
|
||||
},
|
||||
};
|
||||
if (!doc.contexts) doc.contexts = [];
|
||||
doc.contexts.push(ctx);
|
||||
} else {
|
||||
ctx.context.user = SA_NAME;
|
||||
ctx.context.namespace = NAMESPACE;
|
||||
}
|
||||
|
||||
writeFileSync(kcPath, YAML.stringify(doc));
|
||||
console.log(
|
||||
`[kube-auth] kubeconfig updated with fresh token for ${SA_NAME} (expires in ${duration})`
|
||||
);
|
||||
}
|
||||
|
||||
export function buildKubeConfig(): KubeConfig {
|
||||
const kc = new KubeConfig();
|
||||
|
||||
const isInCluster =
|
||||
process.env.KUBERNETES_SERVICE_HOST &&
|
||||
existsSync("/var/run/secrets/kubernetes.io/serviceaccount/token");
|
||||
|
||||
if (isInCluster) {
|
||||
console.log("[kube-auth] Running in-cluster, loading from service account");
|
||||
kc.loadFromCluster();
|
||||
return kc;
|
||||
}
|
||||
|
||||
console.log("[kube-auth] Running locally, using ServiceAccount token auth");
|
||||
refreshSaToken();
|
||||
|
||||
setInterval(refreshSaToken, TOKEN_REFRESH_MIN * 60_000);
|
||||
|
||||
kc.loadFromDefault();
|
||||
try {
|
||||
kc.setCurrentContext("bun-local");
|
||||
} catch (_error) {
|
||||
console.warn("[kube-auth] Could not set bun-local context, using default");
|
||||
}
|
||||
|
||||
return kc;
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
type AuthContext = {
|
||||
user?: { role?: string | null } | null;
|
||||
set: { status?: number | string; headers?: unknown };
|
||||
params: Record<string, string>;
|
||||
query: Record<string, string>;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
|
||||
type ErrorResponse = { error: string };
|
||||
|
||||
export const requireAuth = <T extends AuthContext, R>(handler: (context: T) => R) => {
|
||||
return (context: T): R | ErrorResponse => {
|
||||
if (!context.user) {
|
||||
context.set.status = 401;
|
||||
return { error: "Unauthorized" };
|
||||
}
|
||||
return handler(context);
|
||||
};
|
||||
};
|
||||
|
||||
export const requireAdmin = <T extends AuthContext, R>(handler: (context: T) => R) => {
|
||||
return (context: T): R | ErrorResponse => {
|
||||
if (!context.user || context.user.role !== "admin") {
|
||||
context.set.status = 403;
|
||||
return { error: "Admin access required" };
|
||||
}
|
||||
return handler(context);
|
||||
};
|
||||
};
|
||||
@@ -1,33 +0,0 @@
|
||||
export function createSensitiveFieldSelector<T extends Record<string, boolean>>(
|
||||
fields: T
|
||||
): T & { api_key?: false } {
|
||||
return {
|
||||
...fields,
|
||||
api_key: false,
|
||||
} as T & { api_key?: false };
|
||||
}
|
||||
|
||||
export function pickDefined<T extends Record<string, unknown>, K extends keyof T>(
|
||||
source: T,
|
||||
keys: K[]
|
||||
): Partial<Pick<T, K>> {
|
||||
return keys.reduce(
|
||||
(result, key) => {
|
||||
if (source[key] !== undefined) {
|
||||
result[key] = source[key];
|
||||
}
|
||||
return result;
|
||||
},
|
||||
{} as Partial<Pick<T, K>>
|
||||
);
|
||||
}
|
||||
|
||||
export function generateApiKey(prefix: string): string {
|
||||
const crypto = require("node:crypto");
|
||||
let token = crypto.randomBytes(64).toString("hex");
|
||||
token = token
|
||||
.split("")
|
||||
.map((char: string) => (Math.random() > 0.5 ? char.toUpperCase() : char))
|
||||
.join("");
|
||||
return `${prefix}${token}`;
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { prisma } from "@minikura/db";
|
||||
import { betterAuth } from "better-auth";
|
||||
import { prismaAdapter } from "better-auth/adapters/prisma";
|
||||
import { prisma } from "@minikura/db";
|
||||
import { admin, openAPI } from "better-auth/plugins";
|
||||
|
||||
export const auth = betterAuth({
|
||||
@@ -1,9 +1,11 @@
|
||||
import type { Elysia } from "elysia";
|
||||
import { DomainError } from "../domain/errors/base.error";
|
||||
import { logger } from "../infrastructure/logger";
|
||||
|
||||
export const errorHandler = (app: Elysia) => {
|
||||
return app.onError(({ error, set }) => {
|
||||
if (error instanceof DomainError) {
|
||||
logger.warn({ code: error.code, message: error.message }, "Domain error occurred");
|
||||
set.status = error.statusCode;
|
||||
return {
|
||||
success: false,
|
||||
@@ -13,6 +15,7 @@ export const errorHandler = (app: Elysia) => {
|
||||
}
|
||||
|
||||
if (error instanceof Error && (error.name === "ValidationError" || error.name === "ZodError")) {
|
||||
logger.warn({ err: error, message: error.message }, "Validation error");
|
||||
set.status = 400;
|
||||
return {
|
||||
success: false,
|
||||
@@ -21,7 +24,7 @@ export const errorHandler = (app: Elysia) => {
|
||||
};
|
||||
}
|
||||
|
||||
console.error("Unhandled error:", error);
|
||||
logger.error({ err: error }, "Unhandled error in API request");
|
||||
|
||||
set.status = 500;
|
||||
return {
|
||||
@@ -1,7 +1,8 @@
|
||||
import { prisma } from "@minikura/db";
|
||||
import { getErrorMessage } from "@minikura/shared/errors";
|
||||
import { Elysia } from "elysia";
|
||||
import { auth } from "../lib/auth";
|
||||
import { getErrorMessage } from "../lib/errors";
|
||||
import { logger } from "../infrastructure/logger";
|
||||
import { auth } from "../middleware/auth";
|
||||
import { bootstrapSchema } from "../schemas/bootstrap.schema";
|
||||
|
||||
export const bootstrapRoutes = new Elysia({ prefix: "/bootstrap" })
|
||||
@@ -37,14 +38,14 @@ export const bootstrapRoutes = new Elysia({ prefix: "/bootstrap" })
|
||||
});
|
||||
|
||||
if (!result.user) {
|
||||
console.error("No user in response:", result);
|
||||
logger.error({ result }, "No user in bootstrap response");
|
||||
set.status = 500;
|
||||
return { message: "Failed to create user" };
|
||||
}
|
||||
|
||||
return { success: true };
|
||||
} catch (err: unknown) {
|
||||
console.error("Bootstrap setup error:", err);
|
||||
logger.error({ err }, "Bootstrap setup failed");
|
||||
set.status = 500;
|
||||
return { message: getErrorMessage(err) };
|
||||
}
|
||||
|
||||
@@ -1,135 +1,80 @@
|
||||
import { labelKeys } from "@minikura/api";
|
||||
import { Elysia } from "elysia";
|
||||
import { authPlugin } from "../lib/auth-plugin";
|
||||
import { requireAuth } from "../lib/middleware";
|
||||
import { K8sService } from "../services/k8s";
|
||||
import { k8sService } from "../application/di-container";
|
||||
import { requireAuth } from "../middleware/auth-guards";
|
||||
import { authPlugin } from "../middleware/auth-plugin";
|
||||
|
||||
export const k8sRoutes = new Elysia({ prefix: "/k8s" })
|
||||
.use(authPlugin)
|
||||
.get(
|
||||
"/status",
|
||||
requireAuth(async () => {
|
||||
const k8sService = K8sService.getInstance();
|
||||
return k8sService.getConnectionInfo();
|
||||
})
|
||||
)
|
||||
.get(
|
||||
"/pods",
|
||||
requireAuth(async () => {
|
||||
const k8sService = K8sService.getInstance();
|
||||
return await k8sService.getPods();
|
||||
})
|
||||
)
|
||||
.get(
|
||||
"/deployments",
|
||||
requireAuth(async () => {
|
||||
const k8sService = K8sService.getInstance();
|
||||
return await k8sService.getDeployments();
|
||||
})
|
||||
)
|
||||
.get(
|
||||
"/statefulsets",
|
||||
requireAuth(async () => {
|
||||
const k8sService = K8sService.getInstance();
|
||||
return await k8sService.getStatefulSets();
|
||||
})
|
||||
)
|
||||
.get(
|
||||
"/services",
|
||||
requireAuth(async () => {
|
||||
const k8sService = K8sService.getInstance();
|
||||
return await k8sService.getServices();
|
||||
})
|
||||
)
|
||||
.get(
|
||||
"/configmaps",
|
||||
requireAuth(async () => {
|
||||
const k8sService = K8sService.getInstance();
|
||||
return await k8sService.getConfigMaps();
|
||||
})
|
||||
)
|
||||
.get(
|
||||
"/ingresses",
|
||||
requireAuth(async () => {
|
||||
const k8sService = K8sService.getInstance();
|
||||
return await k8sService.getIngresses();
|
||||
})
|
||||
)
|
||||
.get(
|
||||
"/minecraft-servers",
|
||||
requireAuth(async () => {
|
||||
const k8sService = K8sService.getInstance();
|
||||
return await k8sService.getMinecraftServers();
|
||||
})
|
||||
)
|
||||
.get(
|
||||
"/reverse-proxy-servers",
|
||||
requireAuth(async () => {
|
||||
const k8sService = K8sService.getInstance();
|
||||
return await k8sService.getReverseProxyServers();
|
||||
})
|
||||
)
|
||||
.get(
|
||||
"/pods/:podName",
|
||||
requireAuth(async ({ params }) => {
|
||||
const k8sService = K8sService.getInstance();
|
||||
return await k8sService.getPodInfo(params.podName);
|
||||
})
|
||||
)
|
||||
.get(
|
||||
"/pods/:podName/logs",
|
||||
requireAuth(async ({ params, query, set }) => {
|
||||
const k8sService = K8sService.getInstance();
|
||||
const options = {
|
||||
container: query.container as string | undefined,
|
||||
tailLines: query.tailLines ? parseInt(query.tailLines as string, 10) : 1000,
|
||||
timestamps: query.timestamps === "true",
|
||||
sinceSeconds: query.sinceSeconds ? parseInt(query.sinceSeconds as string, 10) : undefined,
|
||||
};
|
||||
const logs = await k8sService.getPodLogs(params.podName, options);
|
||||
.use(requireAuth)
|
||||
.get("/status", async () => {
|
||||
return k8sService.getConnectionInfo();
|
||||
})
|
||||
.get("/pods", async () => {
|
||||
return await k8sService.getPods();
|
||||
})
|
||||
.get("/deployments", async () => {
|
||||
return await k8sService.getDeployments();
|
||||
})
|
||||
.get("/statefulsets", async () => {
|
||||
return await k8sService.getStatefulSets();
|
||||
})
|
||||
.get("/services", async () => {
|
||||
return await k8sService.getServices();
|
||||
})
|
||||
.get("/configmaps", async () => {
|
||||
return await k8sService.getConfigMaps();
|
||||
})
|
||||
.get("/ingresses", async () => {
|
||||
return await k8sService.getIngresses();
|
||||
})
|
||||
.get("/minecraft-servers", async () => {
|
||||
return await k8sService.getMinecraftServers();
|
||||
})
|
||||
.get("/reverse-proxy-servers", async () => {
|
||||
return await k8sService.getReverseProxyServers();
|
||||
})
|
||||
.get("/pods/:podName", async ({ params }) => {
|
||||
return await k8sService.getPodInfo(params.podName);
|
||||
})
|
||||
.get("/pods/:podName/logs", async ({ params, query, set }) => {
|
||||
const options = {
|
||||
container: query.container as string | undefined,
|
||||
tailLines: query.tailLines ? parseInt(query.tailLines as string, 10) : 1000,
|
||||
timestamps: query.timestamps === "true",
|
||||
sinceSeconds: query.sinceSeconds ? parseInt(query.sinceSeconds as string, 10) : undefined,
|
||||
};
|
||||
const logs = await k8sService.getPodLogs(params.podName, options);
|
||||
|
||||
// Return as plain text
|
||||
const headers = (set.headers ?? {}) as Record<string, string>;
|
||||
headers["content-type"] = "text/plain";
|
||||
set.headers = headers;
|
||||
return logs;
|
||||
})
|
||||
)
|
||||
.get(
|
||||
"/servers/:serverId/pods",
|
||||
requireAuth(async ({ params }) => {
|
||||
const k8sService = K8sService.getInstance();
|
||||
const labelSelector = `minikura.kirameki.cafe/server-id=${params.serverId}`;
|
||||
return await k8sService.getPodsByLabel(labelSelector);
|
||||
})
|
||||
)
|
||||
.get(
|
||||
"/reverse-proxy/:serverId/pods",
|
||||
requireAuth(async ({ params }) => {
|
||||
const k8sService = K8sService.getInstance();
|
||||
// Reverse proxy servers use either 'velocity-{id}' or 'bungeecord-{id}' pattern
|
||||
// We need to check both patterns or use the proxy-id label
|
||||
const labelSelector = `minikura.kirameki.cafe/proxy-id=${params.serverId}`;
|
||||
return await k8sService.getPodsByLabel(labelSelector);
|
||||
})
|
||||
)
|
||||
.get(
|
||||
"/services/:serviceName",
|
||||
requireAuth(async ({ params }) => {
|
||||
const k8sService = K8sService.getInstance();
|
||||
return await k8sService.getServiceInfo(params.serviceName);
|
||||
})
|
||||
)
|
||||
.get(
|
||||
"/services/:serviceName/connection-info",
|
||||
requireAuth(async ({ params }) => {
|
||||
const k8sService = K8sService.getInstance();
|
||||
return await k8sService.getServerConnectionInfo(params.serviceName);
|
||||
})
|
||||
)
|
||||
.get(
|
||||
"/nodes",
|
||||
requireAuth(async () => {
|
||||
const k8sService = K8sService.getInstance();
|
||||
return await k8sService.getNodes();
|
||||
})
|
||||
// Return as plain text
|
||||
const headers = (set.headers ?? {}) as Record<string, string>;
|
||||
headers["content-type"] = "text/plain";
|
||||
set.headers = headers;
|
||||
return logs;
|
||||
})
|
||||
.get("/servers/:serverId/pods", async ({ params }) => {
|
||||
const labelSelector = `${labelKeys.serverId}=${params.serverId}`;
|
||||
return await k8sService.getPodsByLabel(labelSelector);
|
||||
})
|
||||
.get("/reverse-proxy/:serverId/pods", async ({ params }) => {
|
||||
const labelSelector = `${labelKeys.proxyId}=${params.serverId}`;
|
||||
return await k8sService.getPodsByLabel(labelSelector);
|
||||
})
|
||||
.get("/services/:serviceName", async ({ params }) => {
|
||||
return await k8sService.getServiceInfo(params.serviceName);
|
||||
})
|
||||
.get("/services/:serviceName/connection-info", async ({ params }) => {
|
||||
return await k8sService.getServerConnectionInfo(params.serviceName);
|
||||
})
|
||||
.get("/nodes", async () => {
|
||||
return await k8sService.getNodes();
|
||||
})
|
||||
.group("/metrics", (app) =>
|
||||
app
|
||||
.get("/pods", async () => {
|
||||
return await k8sService.getPodMetrics();
|
||||
})
|
||||
.get("/nodes", async () => {
|
||||
return await k8sService.getNodeMetrics();
|
||||
})
|
||||
);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Elysia } from "elysia";
|
||||
import { z } from "zod";
|
||||
import { reverseProxyService } from "../application/di-container";
|
||||
import { requireAuth } from "../middleware/auth-guards";
|
||||
import { createReverseProxySchema, updateReverseProxySchema } from "../schemas/server.schema";
|
||||
|
||||
const envVariableSchema = z.object({
|
||||
@@ -9,6 +10,7 @@ const envVariableSchema = z.object({
|
||||
});
|
||||
|
||||
export const reverseProxyRoutes = new Elysia({ prefix: "/reverse-proxy" })
|
||||
.use(requireAuth)
|
||||
.get("/", async () => {
|
||||
return await reverseProxyService.getAllReverseProxies(false);
|
||||
})
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Elysia } from "elysia";
|
||||
import { z } from "zod";
|
||||
import { serverService, wsService } from "../application/di-container";
|
||||
import { requireAuth } from "../middleware/auth-guards";
|
||||
import { createServerSchema, updateServerSchema } from "../schemas/server.schema";
|
||||
import type { WebSocketClient } from "../services/websocket";
|
||||
|
||||
@@ -23,6 +24,7 @@ export const serverRoutes = new Elysia({ prefix: "/servers" })
|
||||
},
|
||||
message() {},
|
||||
})
|
||||
.use(requireAuth)
|
||||
.get("/", async () => {
|
||||
return await serverService.getAllServers(false);
|
||||
})
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import * as k8s from "@kubernetes/client-node";
|
||||
import { getErrorMessage } from "@minikura/shared/errors";
|
||||
import { Elysia } from "elysia";
|
||||
import { getErrorMessage } from "../lib/errors";
|
||||
import { K8sService } from "../services/k8s";
|
||||
import { k8sService } from "../application/di-container";
|
||||
import { logger } from "../infrastructure/logger";
|
||||
|
||||
type TerminalWsData = {
|
||||
query?: Record<string, string>;
|
||||
@@ -32,7 +32,7 @@ export const terminalRoutes = new Elysia({ prefix: "/terminal" }).ws("/exec", {
|
||||
const shell = ws.data.query?.shell || "/bin/sh";
|
||||
const mode = ws.data.query?.mode || "shell";
|
||||
|
||||
console.log(
|
||||
logger.debug(
|
||||
`Opening terminal for pod: ${podName}, container: ${container}, shell: ${shell}, mode: ${mode}`
|
||||
);
|
||||
|
||||
@@ -48,7 +48,6 @@ export const terminalRoutes = new Elysia({ prefix: "/terminal" }).ws("/exec", {
|
||||
}
|
||||
|
||||
try {
|
||||
const k8sService = K8sService.getInstance();
|
||||
if (!k8sService.isInitialized()) {
|
||||
ws.send(
|
||||
JSON.stringify({
|
||||
@@ -94,7 +93,7 @@ export const terminalRoutes = new Elysia({ prefix: "/terminal" }).ws("/exec", {
|
||||
.replace("https://", "wss://")
|
||||
.replace("http://", "ws://");
|
||||
|
||||
console.log(`Connecting to Kubernetes: ${wsUrl}`);
|
||||
logger.debug(`Connecting to Kubernetes: ${wsUrl}`);
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
Connection: "Upgrade",
|
||||
@@ -107,10 +106,10 @@ export const terminalRoutes = new Elysia({ prefix: "/terminal" }).ws("/exec", {
|
||||
};
|
||||
|
||||
if (user?.token) {
|
||||
headers["Authorization"] = `Bearer ${user.token}`;
|
||||
headers.Authorization = `Bearer ${user.token}`;
|
||||
} else if (user?.username && user?.password) {
|
||||
const auth = Buffer.from(`${user.username}:${user.password}`).toString("base64");
|
||||
headers["Authorization"] = `Basic ${auth}`;
|
||||
headers.Authorization = `Basic ${auth}`;
|
||||
}
|
||||
|
||||
const tlsOptions: BunTlsOptions = {
|
||||
@@ -132,7 +131,7 @@ export const terminalRoutes = new Elysia({ prefix: "/terminal" }).ws("/exec", {
|
||||
ws.data.k8sWs = k8sWs;
|
||||
|
||||
k8sWs.onopen = async () => {
|
||||
console.log(`Connected to Kubernetes ${isAttach ? "attach" : "exec"}`);
|
||||
logger.debug(`Connected to Kubernetes ${isAttach ? "attach" : "exec"}`);
|
||||
|
||||
if (isAttach) {
|
||||
try {
|
||||
@@ -149,7 +148,7 @@ export const terminalRoutes = new Elysia({ prefix: "/terminal" }).ws("/exec", {
|
||||
ws.send(
|
||||
JSON.stringify({
|
||||
type: "output",
|
||||
data: line + "\r\n",
|
||||
data: `${line}\r\n`,
|
||||
})
|
||||
);
|
||||
}
|
||||
@@ -162,7 +161,7 @@ export const terminalRoutes = new Elysia({ prefix: "/terminal" }).ws("/exec", {
|
||||
})
|
||||
);
|
||||
} catch (logError) {
|
||||
console.error("Failed to fetch historical logs:", logError);
|
||||
logger.error("Failed to fetch historical logs:", logError);
|
||||
ws.send(
|
||||
JSON.stringify({
|
||||
type: "ready",
|
||||
@@ -202,13 +201,18 @@ export const terminalRoutes = new Elysia({ prefix: "/terminal" }).ws("/exec", {
|
||||
ws.send(JSON.stringify({ type: "output", data }));
|
||||
return;
|
||||
} else {
|
||||
console.log("Unknown data type:", typeof data, "constructor:", data?.constructor?.name);
|
||||
logger.debug(
|
||||
"Unknown data type:",
|
||||
typeof data,
|
||||
"constructor:",
|
||||
data?.constructor?.name
|
||||
);
|
||||
buffer = new Uint8Array(data);
|
||||
}
|
||||
|
||||
processBuffer(buffer);
|
||||
} catch (err) {
|
||||
console.error("Error processing Kubernetes message:", err);
|
||||
logger.error("Error processing Kubernetes message:", err);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -223,13 +227,13 @@ export const terminalRoutes = new Elysia({ prefix: "/terminal" }).ws("/exec", {
|
||||
if (channel === 1 || channel === 2) {
|
||||
ws.send(JSON.stringify({ type: "output", data: message }));
|
||||
} else if (channel === 3) {
|
||||
console.error("Kubernetes error channel:", message);
|
||||
logger.error("Kubernetes error channel:", message);
|
||||
ws.send(JSON.stringify({ type: "error", data: message }));
|
||||
}
|
||||
}
|
||||
|
||||
k8sWs.onerror = (error: Event) => {
|
||||
console.error("Kubernetes WebSocket error:", error);
|
||||
logger.error("Kubernetes WebSocket error:", error);
|
||||
const message = getErrorMessage(error);
|
||||
ws.send(
|
||||
JSON.stringify({
|
||||
@@ -240,7 +244,7 @@ export const terminalRoutes = new Elysia({ prefix: "/terminal" }).ws("/exec", {
|
||||
};
|
||||
|
||||
k8sWs.onclose = (event: CloseEvent) => {
|
||||
console.log(`Kubernetes WebSocket closed: ${event.code} ${event.reason}`);
|
||||
logger.debug(`Kubernetes WebSocket closed: ${event.code} ${event.reason}`);
|
||||
ws.send(
|
||||
JSON.stringify({
|
||||
type: "close",
|
||||
@@ -250,9 +254,9 @@ export const terminalRoutes = new Elysia({ prefix: "/terminal" }).ws("/exec", {
|
||||
ws.close();
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
console.error("Error setting up terminal:", error);
|
||||
logger.error("Error setting up terminal:", error);
|
||||
if (error instanceof Error) {
|
||||
console.error("Error stack:", error.stack);
|
||||
logger.error("Error stack:", error.stack);
|
||||
}
|
||||
ws.send(
|
||||
JSON.stringify({
|
||||
@@ -274,12 +278,12 @@ export const terminalRoutes = new Elysia({ prefix: "/terminal" }).ws("/exec", {
|
||||
const k8sWs = ws.data.k8sWs;
|
||||
|
||||
if (!k8sWs || k8sWs.readyState !== WebSocket.OPEN) {
|
||||
console.error("Kubernetes WebSocket not ready, state:", k8sWs?.readyState);
|
||||
logger.error("Kubernetes WebSocket not ready, state:", k8sWs?.readyState);
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.type === "input") {
|
||||
console.log("Sending input to k8s:", data.data);
|
||||
logger.debug("Sending input to k8s:", data.data);
|
||||
const encoder = new TextEncoder();
|
||||
const textData = encoder.encode(data.data);
|
||||
const buffer = new Uint8Array(1 + textData.length);
|
||||
@@ -299,7 +303,7 @@ export const terminalRoutes = new Elysia({ prefix: "/terminal" }).ws("/exec", {
|
||||
k8sWs.send(buffer.buffer);
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
console.error("Error handling terminal message:", error);
|
||||
logger.error("Error handling terminal message:", error);
|
||||
ws.send(
|
||||
JSON.stringify({
|
||||
type: "error",
|
||||
@@ -310,7 +314,7 @@ export const terminalRoutes = new Elysia({ prefix: "/terminal" }).ws("/exec", {
|
||||
},
|
||||
|
||||
close: (ws: TerminalWs) => {
|
||||
console.log("Client WebSocket closed");
|
||||
logger.debug("Client WebSocket closed");
|
||||
const k8sWs = ws.data.k8sWs;
|
||||
if (k8sWs && k8sWs.readyState === WebSocket.OPEN) {
|
||||
k8sWs.close();
|
||||
@@ -324,7 +328,7 @@ function parseTerminalMessage(message: unknown): TerminalMessage | null {
|
||||
const parsed = JSON.parse(message) as unknown;
|
||||
return isTerminalMessage(parsed) ? parsed : null;
|
||||
} catch {
|
||||
console.error("Failed to parse message as JSON:", message);
|
||||
logger.error("Failed to parse message as JSON:", message);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { UpdateUserInput } from "@minikura/db";
|
||||
import { Elysia } from "elysia";
|
||||
import { userService } from "../application/di-container";
|
||||
import { requireAdmin, requireAuth } from "../lib/authorization";
|
||||
import { requireAdmin, requireAuth } from "../middleware/auth-guards";
|
||||
|
||||
export const userRoutes = new Elysia({ prefix: "/users" })
|
||||
.use(requireAdmin)
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
import { MinecraftServerJarType, ReverseProxyServerType, ServerType, ServiceType } from "@minikura/db";
|
||||
import {
|
||||
MinecraftServerJarType,
|
||||
ReverseProxyServerType,
|
||||
ServerType,
|
||||
ServiceType,
|
||||
} from "@minikura/db";
|
||||
import { z } from "zod";
|
||||
import { GameMode, ServerDifficulty } from "../domain/entities/enums";
|
||||
|
||||
|
||||
@@ -1,235 +0,0 @@
|
||||
import { describe, it, expect, beforeEach, mock } from "bun:test";
|
||||
import { SessionService } from "../session";
|
||||
|
||||
// Create mock functions
|
||||
const mockSessionFindUnique = mock();
|
||||
const mockServerFindUnique = mock();
|
||||
const mockReverseProxyFindUnique = mock();
|
||||
const mockIsUserSuspended = mock();
|
||||
|
||||
// Mock the prisma client
|
||||
mock.module("@minikura/db", () => ({
|
||||
prisma: {
|
||||
session: {
|
||||
findUnique: mockSessionFindUnique,
|
||||
},
|
||||
server: {
|
||||
findUnique: mockServerFindUnique,
|
||||
},
|
||||
reverseProxyServer: {
|
||||
findUnique: mockReverseProxyFindUnique,
|
||||
},
|
||||
},
|
||||
isUserSuspended: mockIsUserSuspended,
|
||||
}));
|
||||
|
||||
// Import mocked modules
|
||||
await import("@minikura/db");
|
||||
|
||||
describe("SessionService", () => {
|
||||
beforeEach(() => {
|
||||
mockSessionFindUnique.mockClear();
|
||||
mockServerFindUnique.mockClear();
|
||||
mockReverseProxyFindUnique.mockClear();
|
||||
mockIsUserSuspended.mockClear();
|
||||
});
|
||||
|
||||
describe("validate", () => {
|
||||
it("should return INVALID for non-existent session", async () => {
|
||||
mockSessionFindUnique.mockResolvedValue(null);
|
||||
|
||||
const result = await SessionService.validate("invalid-token");
|
||||
|
||||
expect(result.status).toBe(SessionService.SESSION_STATUS.INVALID);
|
||||
expect(result.session).toBeNull();
|
||||
});
|
||||
|
||||
it("should return EXPIRED for expired session", async () => {
|
||||
const expiredDate = new Date(Date.now() - 1000);
|
||||
mockSessionFindUnique.mockResolvedValue({
|
||||
id: "session-1",
|
||||
token: "token-1",
|
||||
expiresAt: expiredDate,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
ipAddress: null,
|
||||
userAgent: null,
|
||||
userId: "user-1",
|
||||
user: {
|
||||
id: "user-1",
|
||||
name: "Test User",
|
||||
email: "test@example.com",
|
||||
emailVerified: true,
|
||||
image: null,
|
||||
role: "user",
|
||||
isSuspended: false,
|
||||
suspendedUntil: null,
|
||||
},
|
||||
});
|
||||
|
||||
const result = await SessionService.validate("expired-token");
|
||||
|
||||
expect(result.status).toBe(SessionService.SESSION_STATUS.EXPIRED);
|
||||
});
|
||||
|
||||
it("should return USER_SUSPENDED for suspended user", async () => {
|
||||
const futureDate = new Date(Date.now() + 1000000);
|
||||
mockIsUserSuspended.mockReturnValue(true);
|
||||
|
||||
mockSessionFindUnique.mockResolvedValue({
|
||||
id: "session-1",
|
||||
token: "token-1",
|
||||
expiresAt: futureDate,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
ipAddress: null,
|
||||
userAgent: null,
|
||||
userId: "user-1",
|
||||
user: {
|
||||
id: "user-1",
|
||||
name: "Test User",
|
||||
email: "test@example.com",
|
||||
emailVerified: true,
|
||||
image: null,
|
||||
role: "user",
|
||||
isSuspended: true,
|
||||
suspendedUntil: null,
|
||||
},
|
||||
});
|
||||
|
||||
const result = await SessionService.validate("valid-token");
|
||||
|
||||
expect(result.status).toBe(SessionService.SESSION_STATUS.USER_SUSPENDED);
|
||||
});
|
||||
|
||||
it("should return VALID for valid session with active user", async () => {
|
||||
const futureDate = new Date(Date.now() + 1000000);
|
||||
mockIsUserSuspended.mockReturnValue(false);
|
||||
|
||||
mockSessionFindUnique.mockResolvedValue({
|
||||
id: "session-1",
|
||||
token: "token-1",
|
||||
expiresAt: futureDate,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
ipAddress: null,
|
||||
userAgent: null,
|
||||
userId: "user-1",
|
||||
user: {
|
||||
id: "user-1",
|
||||
name: "Test User",
|
||||
email: "test@example.com",
|
||||
emailVerified: true,
|
||||
image: null,
|
||||
role: "user",
|
||||
isSuspended: false,
|
||||
suspendedUntil: null,
|
||||
},
|
||||
});
|
||||
|
||||
const result = await SessionService.validate("valid-token");
|
||||
|
||||
expect(result.status).toBe(SessionService.SESSION_STATUS.VALID);
|
||||
expect(result.session).toBeDefined();
|
||||
});
|
||||
|
||||
it("should handle temporary suspension correctly", async () => {
|
||||
const futureDate = new Date(Date.now() + 1000000);
|
||||
const pastSuspensionDate = new Date(Date.now() - 1000);
|
||||
|
||||
// User was suspended but suspension has expired
|
||||
mockIsUserSuspended.mockReturnValue(false);
|
||||
|
||||
mockSessionFindUnique.mockResolvedValue({
|
||||
id: "session-1",
|
||||
token: "token-1",
|
||||
expiresAt: futureDate,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
ipAddress: null,
|
||||
userAgent: null,
|
||||
userId: "user-1",
|
||||
user: {
|
||||
id: "user-1",
|
||||
name: "Test User",
|
||||
email: "test@example.com",
|
||||
emailVerified: true,
|
||||
image: null,
|
||||
role: "user",
|
||||
isSuspended: true,
|
||||
suspendedUntil: pastSuspensionDate,
|
||||
},
|
||||
});
|
||||
|
||||
const result = await SessionService.validate("valid-token");
|
||||
|
||||
expect(result.status).toBe(SessionService.SESSION_STATUS.VALID);
|
||||
});
|
||||
});
|
||||
|
||||
describe("validateApiKey", () => {
|
||||
it("should return INVALID for invalid API key format", async () => {
|
||||
const result = await SessionService.validateApiKey("invalid-key");
|
||||
|
||||
expect(result.status).toBe(SessionService.SESSION_STATUS.INVALID);
|
||||
expect(result.server).toBeNull();
|
||||
});
|
||||
|
||||
it("should return INVALID when reverse proxy server not found", async () => {
|
||||
mockReverseProxyFindUnique.mockResolvedValue(null);
|
||||
|
||||
const result = await SessionService.validateApiKey(
|
||||
"minikura_reverse_proxy_server_api_key_invalid"
|
||||
);
|
||||
|
||||
expect(result.status).toBe(SessionService.SESSION_STATUS.INVALID);
|
||||
expect(result.server).toBeNull();
|
||||
});
|
||||
|
||||
it("should return valid reverse proxy server for valid API key", async () => {
|
||||
const mockServer = {
|
||||
id: "server-1",
|
||||
subdomain: "test",
|
||||
api_key: "minikura_reverse_proxy_server_api_key_valid",
|
||||
type: "VELOCITY",
|
||||
description: null,
|
||||
memory: "1G",
|
||||
external_address: "test.example.com",
|
||||
external_port: 25565,
|
||||
listen_port: 25577,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
};
|
||||
|
||||
mockReverseProxyFindUnique.mockResolvedValue(mockServer);
|
||||
|
||||
const result = await SessionService.validateApiKey(
|
||||
"minikura_reverse_proxy_server_api_key_valid"
|
||||
);
|
||||
|
||||
expect(result.status).toBe(SessionService.SESSION_STATUS.VALID);
|
||||
expect(result.server?.id).toBe(mockServer.id);
|
||||
});
|
||||
|
||||
it("should return valid server for valid server API key", async () => {
|
||||
const mockServer = {
|
||||
id: "server-1",
|
||||
name: "Test Server",
|
||||
api_key: "minikura_server_api_key_valid",
|
||||
type: "STATEFUL",
|
||||
description: null,
|
||||
memory: "2G",
|
||||
listen_port: 25565,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
};
|
||||
|
||||
mockServerFindUnique.mockResolvedValue(mockServer);
|
||||
|
||||
const result = await SessionService.validateApiKey("minikura_server_api_key_valid");
|
||||
|
||||
expect(result.status).toBe(SessionService.SESSION_STATUS.VALID);
|
||||
expect(result.server?.id).toBe(mockServer.id);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,272 +0,0 @@
|
||||
import { beforeEach, describe, expect, it, mock } from "bun:test";
|
||||
import { UserService } from "../user";
|
||||
|
||||
// Create mock functions
|
||||
const mockFindUnique = mock();
|
||||
const mockFindMany = mock();
|
||||
const mockUpdate = mock();
|
||||
const mockDelete = mock();
|
||||
const mockIsUserSuspended = mock();
|
||||
|
||||
// Mock the prisma client
|
||||
mock.module("@minikura/db", () => ({
|
||||
prisma: {
|
||||
user: {
|
||||
findUnique: mockFindUnique,
|
||||
findMany: mockFindMany,
|
||||
update: mockUpdate,
|
||||
delete: mockDelete,
|
||||
},
|
||||
},
|
||||
isUserSuspended: mockIsUserSuspended,
|
||||
}));
|
||||
|
||||
// Import mocked modules
|
||||
await import("@minikura/db");
|
||||
|
||||
describe("UserService", () => {
|
||||
beforeEach(() => {
|
||||
mockFindUnique.mockClear();
|
||||
mockFindMany.mockClear();
|
||||
mockUpdate.mockClear();
|
||||
mockDelete.mockClear();
|
||||
mockIsUserSuspended.mockClear();
|
||||
});
|
||||
|
||||
describe("getUserByEmail", () => {
|
||||
it("should return user when found", async () => {
|
||||
const mockUser = {
|
||||
id: "user-1",
|
||||
name: "Test User",
|
||||
email: "test@example.com",
|
||||
emailVerified: true,
|
||||
image: null,
|
||||
role: "user",
|
||||
banned: false,
|
||||
isSuspended: false,
|
||||
suspendedUntil: null,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
};
|
||||
|
||||
mockFindUnique.mockResolvedValue(mockUser);
|
||||
|
||||
const result = await UserService.getUserByEmail("test@example.com");
|
||||
|
||||
expect(mockFindUnique).toHaveBeenCalledWith({
|
||||
where: { email: "test@example.com" },
|
||||
});
|
||||
expect(result).toEqual(mockUser);
|
||||
});
|
||||
|
||||
it("should return null when user not found", async () => {
|
||||
mockFindUnique.mockResolvedValue(null);
|
||||
|
||||
const result = await UserService.getUserByEmail("notfound@example.com");
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("getUserById", () => {
|
||||
it("should return user when found", async () => {
|
||||
const mockUser = {
|
||||
id: "user-1",
|
||||
name: "Test User",
|
||||
email: "test@example.com",
|
||||
emailVerified: true,
|
||||
image: null,
|
||||
role: "user",
|
||||
banned: false,
|
||||
isSuspended: false,
|
||||
suspendedUntil: null,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
};
|
||||
|
||||
mockFindUnique.mockResolvedValue(mockUser);
|
||||
|
||||
const result = await UserService.getUserById("user-1");
|
||||
|
||||
expect(result).toEqual(mockUser);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getAllUsersWithSuspension", () => {
|
||||
it("should return all users with suspension info", async () => {
|
||||
const mockUsers = [
|
||||
{
|
||||
id: "user-1",
|
||||
name: "User 1",
|
||||
email: "user1@example.com",
|
||||
emailVerified: true,
|
||||
image: null,
|
||||
role: "user",
|
||||
banned: false,
|
||||
isSuspended: false,
|
||||
suspendedUntil: null,
|
||||
createdAt: new Date(),
|
||||
},
|
||||
{
|
||||
id: "user-2",
|
||||
name: "User 2",
|
||||
email: "user2@example.com",
|
||||
emailVerified: true,
|
||||
image: null,
|
||||
role: "user",
|
||||
banned: false,
|
||||
isSuspended: true,
|
||||
suspendedUntil: new Date(Date.now() + 86400000),
|
||||
createdAt: new Date(),
|
||||
},
|
||||
];
|
||||
|
||||
mockFindMany.mockResolvedValue(mockUsers);
|
||||
|
||||
const result = await UserService.getAllUsersWithSuspension();
|
||||
|
||||
expect(result).toEqual(mockUsers);
|
||||
expect(result).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("updateUser", () => {
|
||||
it("should update user basic information", async () => {
|
||||
const mockUpdatedUser = {
|
||||
id: "user-1",
|
||||
name: "Updated Name",
|
||||
email: "test@example.com",
|
||||
emailVerified: true,
|
||||
image: null,
|
||||
role: "admin",
|
||||
createdAt: new Date(),
|
||||
};
|
||||
|
||||
mockUpdate.mockResolvedValue(mockUpdatedUser);
|
||||
|
||||
const result = await UserService.updateUser("user-1", {
|
||||
name: "Updated Name",
|
||||
role: "admin",
|
||||
});
|
||||
|
||||
expect(result).toEqual(mockUpdatedUser);
|
||||
});
|
||||
});
|
||||
|
||||
describe("suspendUser", () => {
|
||||
it("should suspend user indefinitely when no expiration provided", async () => {
|
||||
const mockSuspendedUser = {
|
||||
id: "user-1",
|
||||
name: "Test User",
|
||||
email: "test@example.com",
|
||||
emailVerified: true,
|
||||
image: null,
|
||||
role: "user",
|
||||
isSuspended: true,
|
||||
suspendedUntil: null,
|
||||
createdAt: new Date(),
|
||||
};
|
||||
|
||||
mockUpdate.mockResolvedValue(mockSuspendedUser);
|
||||
|
||||
const result = await UserService.suspendUser("user-1");
|
||||
|
||||
expect(result.isSuspended).toBe(true);
|
||||
expect(result.suspendedUntil).toBeNull();
|
||||
});
|
||||
|
||||
it("should suspend user until specific date", async () => {
|
||||
const suspendUntil = new Date(Date.now() + 86400000); // 1 day from now
|
||||
|
||||
const mockSuspendedUser = {
|
||||
id: "user-1",
|
||||
name: "Test User",
|
||||
email: "test@example.com",
|
||||
emailVerified: true,
|
||||
image: null,
|
||||
role: "user",
|
||||
isSuspended: true,
|
||||
suspendedUntil: suspendUntil,
|
||||
createdAt: new Date(),
|
||||
};
|
||||
|
||||
mockUpdate.mockResolvedValue(mockSuspendedUser);
|
||||
|
||||
const result = await UserService.suspendUser("user-1", suspendUntil);
|
||||
|
||||
expect(result.isSuspended).toBe(true);
|
||||
expect(result.suspendedUntil).toEqual(suspendUntil);
|
||||
});
|
||||
});
|
||||
|
||||
describe("unsuspendUser", () => {
|
||||
it("should unsuspend a user", async () => {
|
||||
const mockUnsuspendedUser = {
|
||||
id: "user-1",
|
||||
name: "Test User",
|
||||
email: "test@example.com",
|
||||
emailVerified: true,
|
||||
image: null,
|
||||
role: "user",
|
||||
isSuspended: false,
|
||||
suspendedUntil: null,
|
||||
createdAt: new Date(),
|
||||
};
|
||||
|
||||
mockUpdate.mockResolvedValue(mockUnsuspendedUser);
|
||||
|
||||
const result = await UserService.unsuspendUser("user-1");
|
||||
|
||||
expect(result.isSuspended).toBe(false);
|
||||
expect(result.suspendedUntil).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("deleteUser", () => {
|
||||
it("should delete a user", async () => {
|
||||
mockDelete.mockResolvedValue({});
|
||||
|
||||
await UserService.deleteUser("user-1");
|
||||
|
||||
expect(mockDelete).toHaveBeenCalledWith({
|
||||
where: { id: "user-1" },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("checkSuspension", () => {
|
||||
it("should return true when user is suspended", async () => {
|
||||
const mockUser = {
|
||||
isSuspended: true,
|
||||
suspendedUntil: null,
|
||||
};
|
||||
|
||||
mockFindUnique.mockResolvedValue(mockUser);
|
||||
mockIsUserSuspended.mockReturnValue(true);
|
||||
|
||||
const result = await UserService.checkSuspension("user-1");
|
||||
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
it("should return false when user is not suspended", async () => {
|
||||
const mockUser = {
|
||||
isSuspended: false,
|
||||
suspendedUntil: null,
|
||||
};
|
||||
|
||||
mockFindUnique.mockResolvedValue(mockUser);
|
||||
mockIsUserSuspended.mockReturnValue(false);
|
||||
|
||||
const result = await UserService.checkSuspension("user-1");
|
||||
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it("should throw error when user not found", async () => {
|
||||
mockFindUnique.mockResolvedValue(null);
|
||||
|
||||
await expect(UserService.checkSuspension("user-1")).rejects.toThrow("User not found");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,13 +1,20 @@
|
||||
import * as k8s from "@kubernetes/client-node";
|
||||
import type { CustomResourceSummary } from "@minikura/api";
|
||||
import { K8sResources } from "./k8s/resources";
|
||||
import { API_GROUP } from "@minikura/api";
|
||||
import { buildKubeConfig } from "@minikura/shared/kube-auth";
|
||||
import type { IK8sService } from "../application/interfaces/k8s.service.interface";
|
||||
import { logger } from "../infrastructure/logger";
|
||||
import { ClusterOperations } from "./kubernetes/operations/cluster.operations";
|
||||
import { CustomResourceOperations } from "./kubernetes/operations/custom-resource.operations";
|
||||
import { NetworkOperations } from "./kubernetes/operations/network.operations";
|
||||
import { PodOperations } from "./kubernetes/operations/pod.operations";
|
||||
import { WorkloadOperations } from "./kubernetes/operations/workload.operations";
|
||||
import { K8sResources } from "./kubernetes/resources";
|
||||
|
||||
const CUSTOM_RESOURCE_GROUP = "minikura.kirameki.cafe";
|
||||
const CUSTOM_RESOURCE_VERSION = "v1alpha1";
|
||||
|
||||
export class K8sService {
|
||||
private static instance: K8sService;
|
||||
private kc: k8s.KubeConfig;
|
||||
export class K8sService implements IK8sService {
|
||||
private kc!: k8s.KubeConfig;
|
||||
private coreApi!: k8s.CoreV1Api;
|
||||
private appsApi!: k8s.AppsV1Api;
|
||||
private customObjectsApi!: k8s.CustomObjectsApi;
|
||||
@@ -16,65 +23,30 @@ export class K8sService {
|
||||
private initialized: boolean = false;
|
||||
private resources!: K8sResources;
|
||||
|
||||
private constructor() {
|
||||
this.kc = new k8s.KubeConfig();
|
||||
private podOps!: PodOperations;
|
||||
private clusterOps!: ClusterOperations;
|
||||
private customResourceOps!: CustomResourceOperations;
|
||||
|
||||
constructor() {
|
||||
this.namespace = process.env.KUBERNETES_NAMESPACE || "minikura";
|
||||
|
||||
try {
|
||||
this.setupConfig();
|
||||
this.kc = buildKubeConfig();
|
||||
this.initializeClients();
|
||||
this.initializeOperations();
|
||||
this.resources = new K8sResources(
|
||||
this.coreApi,
|
||||
this.appsApi,
|
||||
this.networkingApi,
|
||||
this.namespace,
|
||||
this.namespace
|
||||
);
|
||||
this.initialized = true;
|
||||
} catch (_error) {
|
||||
} catch (error) {
|
||||
logger.error({ err: error }, "Failed to initialize Kubernetes client");
|
||||
this.initialized = false;
|
||||
}
|
||||
}
|
||||
|
||||
private setupConfig(): void {
|
||||
const isBun = typeof Bun !== "undefined";
|
||||
|
||||
if (isBun) {
|
||||
const { buildKubeConfig } = require("../lib/kube-auth");
|
||||
this.kc = buildKubeConfig();
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
this.kc.loadFromDefault();
|
||||
console.log("Loaded Kubernetes config from default location");
|
||||
} catch (err) {
|
||||
console.warn(
|
||||
"Failed to load Kubernetes config from default location:",
|
||||
err,
|
||||
);
|
||||
}
|
||||
|
||||
if (!this.kc.getCurrentContext()) {
|
||||
try {
|
||||
this.kc.loadFromCluster();
|
||||
console.log("Loaded Kubernetes config from cluster");
|
||||
} catch (err) {
|
||||
console.warn("Failed to load Kubernetes config from cluster:", err);
|
||||
}
|
||||
}
|
||||
|
||||
if (!this.kc.getCurrentContext()) {
|
||||
throw new Error(
|
||||
"Failed to setup Kubernetes client - no valid configuration found",
|
||||
);
|
||||
}
|
||||
|
||||
const currentCluster = this.kc.getCurrentCluster();
|
||||
if (currentCluster) {
|
||||
console.log(`Connecting to Kubernetes server: ${currentCluster.server}`);
|
||||
}
|
||||
}
|
||||
|
||||
private initializeClients(): void {
|
||||
this.coreApi = this.kc.makeApiClient(k8s.CoreV1Api);
|
||||
this.appsApi = this.kc.makeApiClient(k8s.AppsV1Api);
|
||||
@@ -82,11 +54,12 @@ export class K8sService {
|
||||
this.networkingApi = this.kc.makeApiClient(k8s.NetworkingV1Api);
|
||||
}
|
||||
|
||||
static getInstance(): K8sService {
|
||||
if (!K8sService.instance) {
|
||||
K8sService.instance = new K8sService();
|
||||
}
|
||||
return K8sService.instance;
|
||||
private initializeOperations(): void {
|
||||
this.podOps = new PodOperations(this.coreApi, this.namespace);
|
||||
this.workloadOps = new WorkloadOperations(this.appsApi, this.namespace);
|
||||
this.networkOps = new NetworkOperations(this.coreApi, this.networkingApi, this.namespace);
|
||||
this.clusterOps = new ClusterOperations(this.coreApi, this.customObjectsApi, this.namespace);
|
||||
this.customResourceOps = new CustomResourceOperations(this.customObjectsApi, this.namespace);
|
||||
}
|
||||
|
||||
isInitialized(): boolean {
|
||||
@@ -118,147 +91,56 @@ export class K8sService {
|
||||
}
|
||||
|
||||
async getPods() {
|
||||
if (!this.initialized) {
|
||||
throw new Error("Kubernetes client not initialized");
|
||||
}
|
||||
|
||||
try {
|
||||
return await this.resources.listPods();
|
||||
} catch (error: unknown) {
|
||||
console.error("Error fetching pods:", error);
|
||||
throw new Error(`Failed to fetch pods: ${getErrorMessage(error)}`);
|
||||
}
|
||||
this.ensureInitialized();
|
||||
return this.resources.listPods();
|
||||
}
|
||||
|
||||
async getDeployments() {
|
||||
if (!this.initialized) {
|
||||
throw new Error("Kubernetes client not initialized");
|
||||
}
|
||||
|
||||
try {
|
||||
return await this.resources.listDeployments();
|
||||
} catch (error: unknown) {
|
||||
console.error("Error fetching deployments:", error);
|
||||
throw new Error(`Failed to fetch deployments: ${getErrorMessage(error)}`);
|
||||
}
|
||||
this.ensureInitialized();
|
||||
return this.resources.listDeployments();
|
||||
}
|
||||
|
||||
async getStatefulSets() {
|
||||
if (!this.initialized) {
|
||||
throw new Error("Kubernetes client not initialized");
|
||||
}
|
||||
|
||||
try {
|
||||
return await this.resources.listStatefulSets();
|
||||
} catch (error: unknown) {
|
||||
console.error("Error fetching statefulsets:", error);
|
||||
throw new Error(
|
||||
`Failed to fetch statefulsets: ${getErrorMessage(error)}`,
|
||||
);
|
||||
}
|
||||
this.ensureInitialized();
|
||||
return this.resources.listStatefulSets();
|
||||
}
|
||||
|
||||
async getServices() {
|
||||
if (!this.initialized) {
|
||||
throw new Error("Kubernetes client not initialized");
|
||||
}
|
||||
|
||||
try {
|
||||
return await this.resources.listServices();
|
||||
} catch (error: unknown) {
|
||||
console.error("Error fetching services:", error);
|
||||
throw new Error(`Failed to fetch services: ${getErrorMessage(error)}`);
|
||||
}
|
||||
this.ensureInitialized();
|
||||
return this.resources.listServices();
|
||||
}
|
||||
|
||||
async getConfigMaps() {
|
||||
if (!this.initialized) {
|
||||
throw new Error("Kubernetes client not initialized");
|
||||
}
|
||||
|
||||
try {
|
||||
return await this.resources.listConfigMaps();
|
||||
} catch (error: unknown) {
|
||||
console.error("Error fetching configmaps:", error);
|
||||
throw new Error(`Failed to fetch configmaps: ${getErrorMessage(error)}`);
|
||||
}
|
||||
this.ensureInitialized();
|
||||
return this.resources.listConfigMaps();
|
||||
}
|
||||
|
||||
async getIngresses() {
|
||||
this.ensureInitialized();
|
||||
return this.resources.listIngresses();
|
||||
}
|
||||
|
||||
private ensureInitialized(): void {
|
||||
if (!this.initialized) {
|
||||
throw new Error("Kubernetes client not initialized");
|
||||
}
|
||||
|
||||
try {
|
||||
return await this.resources.listIngresses();
|
||||
} catch (error: unknown) {
|
||||
console.error("Error fetching ingresses:", error);
|
||||
throw new Error(`Failed to fetch ingresses: ${getErrorMessage(error)}`);
|
||||
}
|
||||
}
|
||||
|
||||
async getCustomResources(
|
||||
group: string,
|
||||
version: string,
|
||||
plural: string,
|
||||
plural: string
|
||||
): Promise<CustomResourceSummary[]> {
|
||||
if (!this.initialized) {
|
||||
throw new Error("Kubernetes client not initialized");
|
||||
}
|
||||
|
||||
try {
|
||||
type CustomResourceItem = {
|
||||
metadata?: {
|
||||
name?: string;
|
||||
namespace?: string;
|
||||
creationTimestamp?: string;
|
||||
labels?: Record<string, string>;
|
||||
};
|
||||
spec?: Record<string, unknown>;
|
||||
status?: { phase?: string; [key: string]: unknown };
|
||||
};
|
||||
|
||||
const response = await this.customObjectsApi.listNamespacedCustomObject({
|
||||
group,
|
||||
version,
|
||||
namespace: this.namespace,
|
||||
plural,
|
||||
});
|
||||
const body = response as unknown as {
|
||||
items?: CustomResourceItem[];
|
||||
body?: { items?: CustomResourceItem[] };
|
||||
};
|
||||
const items = body.items ?? body.body?.items ?? [];
|
||||
return items.map((item) => ({
|
||||
name: item.metadata?.name,
|
||||
namespace: item.metadata?.namespace,
|
||||
age: getAge(item.metadata?.creationTimestamp),
|
||||
labels: item.metadata?.labels,
|
||||
spec: item.spec,
|
||||
status: item.status,
|
||||
}));
|
||||
} catch (error: unknown) {
|
||||
console.error(`Error fetching custom resources ${plural}:`, error);
|
||||
throw new Error(
|
||||
`Failed to fetch custom resources: ${getErrorMessage(error)}`,
|
||||
);
|
||||
}
|
||||
this.ensureInitialized();
|
||||
return this.customResourceOps.listCustomResources(group, version, plural);
|
||||
}
|
||||
|
||||
async getMinecraftServers() {
|
||||
return this.getCustomResources(
|
||||
CUSTOM_RESOURCE_GROUP,
|
||||
CUSTOM_RESOURCE_VERSION,
|
||||
"minecraftservers",
|
||||
);
|
||||
return this.getCustomResources(API_GROUP, CUSTOM_RESOURCE_VERSION, "minecraftservers");
|
||||
}
|
||||
|
||||
async getReverseProxyServers() {
|
||||
return this.getCustomResources(
|
||||
CUSTOM_RESOURCE_GROUP,
|
||||
CUSTOM_RESOURCE_VERSION,
|
||||
"reverseproxyservers",
|
||||
);
|
||||
return this.getCustomResources(API_GROUP, CUSTOM_RESOURCE_VERSION, "reverseproxyservers");
|
||||
}
|
||||
|
||||
async getPodLogs(
|
||||
@@ -268,150 +150,82 @@ export class K8sService {
|
||||
tailLines?: number;
|
||||
timestamps?: boolean;
|
||||
sinceSeconds?: number;
|
||||
},
|
||||
}
|
||||
) {
|
||||
if (!this.initialized) {
|
||||
throw new Error("Kubernetes client not initialized");
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await this.coreApi.readNamespacedPodLog({
|
||||
name: podName,
|
||||
namespace: this.namespace,
|
||||
container: options?.container,
|
||||
tailLines: options?.tailLines,
|
||||
timestamps: options?.timestamps,
|
||||
sinceSeconds: options?.sinceSeconds,
|
||||
});
|
||||
return response;
|
||||
} catch (error: unknown) {
|
||||
console.error(`Error fetching logs for pod ${podName}:`, error);
|
||||
throw new Error(`Failed to fetch pod logs: ${getErrorMessage(error)}`);
|
||||
}
|
||||
this.ensureInitialized();
|
||||
return this.podOps.getPodLogs(podName, options);
|
||||
}
|
||||
|
||||
async getPodsByLabel(labelSelector: string) {
|
||||
if (!this.initialized) {
|
||||
throw new Error("Kubernetes client not initialized");
|
||||
}
|
||||
|
||||
try {
|
||||
return await this.resources.listPodsByLabel(labelSelector);
|
||||
} catch (error: unknown) {
|
||||
console.error("Error fetching pods by label:", error);
|
||||
throw new Error(
|
||||
`Failed to fetch pods by label: ${getErrorMessage(error)}`,
|
||||
);
|
||||
}
|
||||
this.ensureInitialized();
|
||||
return this.resources.listPodsByLabel(labelSelector);
|
||||
}
|
||||
|
||||
async getPodInfo(podName: string) {
|
||||
if (!this.initialized) {
|
||||
throw new Error("Kubernetes client not initialized");
|
||||
}
|
||||
|
||||
try {
|
||||
return await this.resources.getPodInfo(podName);
|
||||
} catch (error: unknown) {
|
||||
console.error(`Error fetching pod ${podName}:`, error);
|
||||
throw new Error(`Failed to fetch pod info: ${getErrorMessage(error)}`);
|
||||
}
|
||||
this.ensureInitialized();
|
||||
return this.resources.getPodInfo(podName);
|
||||
}
|
||||
|
||||
async getServiceInfo(serviceName: string) {
|
||||
if (!this.initialized) {
|
||||
throw new Error("Kubernetes client not initialized");
|
||||
}
|
||||
|
||||
try {
|
||||
return await this.resources.getServiceInfo(serviceName);
|
||||
} catch (error: unknown) {
|
||||
console.error(`Error fetching service ${serviceName}:`, error);
|
||||
throw new Error(
|
||||
`Failed to fetch service info: ${getErrorMessage(error)}`,
|
||||
);
|
||||
}
|
||||
this.ensureInitialized();
|
||||
return this.resources.getServiceInfo(serviceName);
|
||||
}
|
||||
|
||||
async getNodes() {
|
||||
if (!this.initialized) {
|
||||
throw new Error("Kubernetes client not initialized");
|
||||
}
|
||||
|
||||
try {
|
||||
return await this.resources.listNodes();
|
||||
} catch (error: unknown) {
|
||||
console.error("Error fetching nodes:", error);
|
||||
throw new Error(`Failed to fetch nodes: ${getErrorMessage(error)}`);
|
||||
}
|
||||
this.ensureInitialized();
|
||||
return this.resources.listNodes();
|
||||
}
|
||||
|
||||
async getServerConnectionInfo(serviceName: string) {
|
||||
if (!this.initialized) {
|
||||
throw new Error("Kubernetes client not initialized");
|
||||
}
|
||||
|
||||
try {
|
||||
const service = await this.getServiceInfo(serviceName);
|
||||
const nodes = await this.getNodes();
|
||||
|
||||
if (service.type === "ClusterIP") {
|
||||
return {
|
||||
type: "ClusterIP",
|
||||
ip: service.clusterIP,
|
||||
port: service.ports[0]?.port || null,
|
||||
connectionString:
|
||||
service.clusterIP && service.ports[0]?.port
|
||||
? `${service.clusterIP}:${service.ports[0].port}`
|
||||
: null,
|
||||
note: "Only accessible within the cluster",
|
||||
};
|
||||
}
|
||||
|
||||
if (service.type === "NodePort") {
|
||||
const nodeIP = nodes[0]?.externalIP || nodes[0]?.internalIP;
|
||||
const nodePort = service.ports[0]?.nodePort;
|
||||
return {
|
||||
type: "NodePort",
|
||||
nodeIP,
|
||||
nodePort,
|
||||
port: service.ports[0]?.port || null,
|
||||
connectionString: nodeIP && nodePort ? `${nodeIP}:${nodePort}` : null,
|
||||
note:
|
||||
nodeIP && !nodes[0]?.externalIP
|
||||
? "Using internal IP (may not be accessible from outside the cluster network)"
|
||||
: "Accessible from any node in the cluster",
|
||||
};
|
||||
}
|
||||
|
||||
if (service.type === "LoadBalancer") {
|
||||
const externalIP =
|
||||
service.loadBalancerIP || service.loadBalancerHostname;
|
||||
return {
|
||||
type: "LoadBalancer",
|
||||
externalIP,
|
||||
port: service.ports[0]?.port || null,
|
||||
connectionString:
|
||||
externalIP && service.ports[0]?.port
|
||||
? `${externalIP}:${service.ports[0].port}`
|
||||
: null,
|
||||
note: !externalIP ? "LoadBalancer IP pending" : null,
|
||||
};
|
||||
}
|
||||
this.ensureInitialized();
|
||||
const service = await this.getServiceInfo(serviceName);
|
||||
const nodes = await this.getNodes();
|
||||
|
||||
if (service.type === "ClusterIP") {
|
||||
return {
|
||||
type: service.type,
|
||||
note: "Unknown service type",
|
||||
type: "ClusterIP",
|
||||
ip: service.clusterIP,
|
||||
port: service.ports[0]?.port || null,
|
||||
connectionString:
|
||||
service.clusterIP && service.ports[0]?.port
|
||||
? `${service.clusterIP}:${service.ports[0].port}`
|
||||
: null,
|
||||
note: "Only accessible within the cluster",
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
console.error(
|
||||
`Error fetching connection info for service ${serviceName}:`,
|
||||
error,
|
||||
);
|
||||
throw new Error(
|
||||
`Failed to fetch connection info: ${getErrorMessage(error)}`,
|
||||
);
|
||||
}
|
||||
|
||||
if (service.type === "NodePort") {
|
||||
const nodeIP = nodes[0]?.externalIP || nodes[0]?.internalIP;
|
||||
const nodePort = service.ports[0]?.nodePort;
|
||||
return {
|
||||
type: "NodePort",
|
||||
nodeIP,
|
||||
nodePort,
|
||||
port: service.ports[0]?.port || null,
|
||||
connectionString: nodeIP && nodePort ? `${nodeIP}:${nodePort}` : null,
|
||||
note:
|
||||
nodeIP && !nodes[0]?.externalIP
|
||||
? "Using internal IP (may not be accessible from outside the cluster network)"
|
||||
: "Accessible from any node in the cluster",
|
||||
};
|
||||
}
|
||||
|
||||
if (service.type === "LoadBalancer") {
|
||||
const externalIP = service.loadBalancerIP || service.loadBalancerHostname;
|
||||
return {
|
||||
type: "LoadBalancer",
|
||||
externalIP,
|
||||
port: service.ports[0]?.port || null,
|
||||
connectionString:
|
||||
externalIP && service.ports[0]?.port ? `${externalIP}:${service.ports[0].port}` : null,
|
||||
note: !externalIP ? "LoadBalancer IP pending" : null,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
type: service.type,
|
||||
note: "Unknown service type",
|
||||
};
|
||||
}
|
||||
|
||||
getKubeConfig(): k8s.KubeConfig {
|
||||
@@ -425,31 +239,35 @@ export class K8sService {
|
||||
getNamespace(): string {
|
||||
return this.namespace;
|
||||
}
|
||||
}
|
||||
|
||||
function getAge(timestamp: Date | string | undefined): string {
|
||||
if (!timestamp) return "unknown";
|
||||
const now = new Date();
|
||||
const created = new Date(timestamp);
|
||||
const diff = now.getTime() - created.getTime();
|
||||
|
||||
const seconds = Math.floor(diff / 1000);
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
const hours = Math.floor(minutes / 60);
|
||||
const days = Math.floor(hours / 24);
|
||||
|
||||
if (days > 0) return `${days}d`;
|
||||
if (hours > 0) return `${hours}h`;
|
||||
if (minutes > 0) return `${minutes}m`;
|
||||
return `${seconds}s`;
|
||||
}
|
||||
|
||||
function getErrorMessage(error: unknown): string {
|
||||
if (error instanceof Error) {
|
||||
return error.message;
|
||||
async getPodMetrics(namespace?: string) {
|
||||
this.ensureInitialized();
|
||||
return this.executeOperationSafe(
|
||||
() => this.podOps.getPodMetrics(this.customObjectsApi, namespace),
|
||||
{ items: [] },
|
||||
"Error fetching pod metrics"
|
||||
);
|
||||
}
|
||||
if (typeof error === "string") {
|
||||
return error;
|
||||
|
||||
async getNodeMetrics() {
|
||||
this.ensureInitialized();
|
||||
return this.executeOperationSafe(
|
||||
() => this.clusterOps.getNodeMetrics(),
|
||||
{ items: [] },
|
||||
"Error fetching node metrics"
|
||||
);
|
||||
}
|
||||
|
||||
private async executeOperationSafe<T>(
|
||||
operation: () => Promise<T>,
|
||||
defaultValue: T,
|
||||
errorContext: string
|
||||
): Promise<T> {
|
||||
try {
|
||||
return await operation();
|
||||
} catch (error: unknown) {
|
||||
logger.error({ err: error, context: errorContext }, "K8s operation failed");
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
return "Unknown error";
|
||||
}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { getErrorMessage } from "@minikura/shared/errors";
|
||||
import { logger } from "../../../infrastructure/logger";
|
||||
|
||||
export abstract class BaseK8sOperations {
|
||||
protected namespace: string;
|
||||
|
||||
constructor(namespace: string) {
|
||||
this.namespace = namespace;
|
||||
}
|
||||
|
||||
protected async executeOperation<T>(
|
||||
operation: () => Promise<T>,
|
||||
errorContext: string
|
||||
): Promise<T> {
|
||||
try {
|
||||
return await operation();
|
||||
} catch (error: unknown) {
|
||||
const errorMessage = getErrorMessage(error);
|
||||
logger.error({ err: error, context: errorContext }, "K8s operation failed");
|
||||
throw new Error(`${errorContext}: ${errorMessage}`);
|
||||
}
|
||||
}
|
||||
|
||||
protected async executeOperationSafe<T>(
|
||||
operation: () => Promise<T>,
|
||||
defaultValue: T,
|
||||
errorContext: string
|
||||
): Promise<T> {
|
||||
try {
|
||||
return await operation();
|
||||
} catch (error: unknown) {
|
||||
logger.error({ err: error, context: errorContext }, "K8s operation failed (safe mode)");
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
|
||||
getNamespace(): string {
|
||||
return this.namespace;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import type * as k8s from "@kubernetes/client-node";
|
||||
import { BaseK8sOperations } from "./base.operations";
|
||||
|
||||
export class ClusterOperations extends BaseK8sOperations {
|
||||
constructor(
|
||||
private coreApi: k8s.CoreV1Api,
|
||||
private customObjectsApi: k8s.CustomObjectsApi,
|
||||
namespace: string
|
||||
) {
|
||||
super(namespace);
|
||||
}
|
||||
|
||||
async listNodes() {
|
||||
return this.executeOperation(
|
||||
() => this.coreApi.listNode().then((r) => r.items),
|
||||
"Failed to fetch nodes"
|
||||
);
|
||||
}
|
||||
|
||||
async getNodeMetrics() {
|
||||
return this.executeOperation(
|
||||
() =>
|
||||
this.customObjectsApi.listClusterCustomObject({
|
||||
group: "metrics.k8s.io",
|
||||
version: "v1beta1",
|
||||
plural: "nodes",
|
||||
}),
|
||||
"Failed to fetch node metrics"
|
||||
);
|
||||
}
|
||||
|
||||
async listConfigMaps(namespace?: string) {
|
||||
const ns = namespace || this.namespace;
|
||||
return this.executeOperation(
|
||||
() => this.coreApi.listNamespacedConfigMap({ namespace: ns }).then((r) => r.items),
|
||||
"Failed to fetch configmaps"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import type * as k8s from "@kubernetes/client-node";
|
||||
import type { CustomResourceSummary } from "@minikura/api";
|
||||
import { getAge } from "@minikura/shared/errors";
|
||||
import { BaseK8sOperations } from "./base.operations";
|
||||
|
||||
interface CustomResourceItem {
|
||||
kind?: string;
|
||||
metadata?: {
|
||||
name?: string;
|
||||
namespace?: string;
|
||||
creationTimestamp?: string;
|
||||
labels?: Record<string, string>;
|
||||
};
|
||||
spec?: Record<string, unknown>;
|
||||
status?: { phase?: string; [key: string]: unknown };
|
||||
}
|
||||
|
||||
interface CustomResourceList {
|
||||
items?: CustomResourceItem[];
|
||||
}
|
||||
|
||||
export class CustomResourceOperations extends BaseK8sOperations {
|
||||
constructor(
|
||||
private customObjectsApi: k8s.CustomObjectsApi,
|
||||
namespace: string
|
||||
) {
|
||||
super(namespace);
|
||||
}
|
||||
|
||||
async listCustomResources(
|
||||
group: string,
|
||||
version: string,
|
||||
plural: string
|
||||
): Promise<CustomResourceSummary[]> {
|
||||
return this.executeOperation(async () => {
|
||||
const response = await this.customObjectsApi.listNamespacedCustomObject({
|
||||
group,
|
||||
version,
|
||||
namespace: this.namespace,
|
||||
plural,
|
||||
});
|
||||
|
||||
const items = (response as unknown as CustomResourceList).items || [];
|
||||
|
||||
return items.map((item) => ({
|
||||
name: item.metadata?.name ?? "",
|
||||
namespace: item.metadata?.namespace ?? this.namespace,
|
||||
age: getAge(item.metadata?.creationTimestamp),
|
||||
labels: item.metadata?.labels,
|
||||
spec: item.spec ?? {},
|
||||
status: item.status ?? {},
|
||||
}));
|
||||
}, `Failed to fetch custom resources (${plural})`);
|
||||
}
|
||||
}
|
||||
6
apps/backend/src/services/kubernetes/operations/index.ts
Normal file
6
apps/backend/src/services/kubernetes/operations/index.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
export { BaseK8sOperations } from "./base.operations";
|
||||
export { ClusterOperations } from "./cluster.operations";
|
||||
export { CustomResourceOperations } from "./custom-resource.operations";
|
||||
export { NetworkOperations } from "./network.operations";
|
||||
export { PodOperations } from "./pod.operations";
|
||||
export { WorkloadOperations } from "./workload.operations";
|
||||
@@ -0,0 +1,89 @@
|
||||
import type * as k8s from "@kubernetes/client-node";
|
||||
import { BaseK8sOperations } from "./base.operations";
|
||||
|
||||
export class NetworkOperations extends BaseK8sOperations {
|
||||
constructor(
|
||||
private coreApi: k8s.CoreV1Api,
|
||||
private networkingApi: k8s.NetworkingV1Api,
|
||||
namespace: string
|
||||
) {
|
||||
super(namespace);
|
||||
}
|
||||
|
||||
async listServices() {
|
||||
return this.executeOperation(
|
||||
() => this.coreApi.listNamespacedService({ namespace: this.namespace }).then((r) => r.items),
|
||||
"Failed to fetch services"
|
||||
);
|
||||
}
|
||||
|
||||
async listIngresses() {
|
||||
return this.executeOperation(
|
||||
() =>
|
||||
this.networkingApi
|
||||
.listNamespacedIngress({ namespace: this.namespace })
|
||||
.then((r) => r.items),
|
||||
"Failed to fetch ingresses"
|
||||
);
|
||||
}
|
||||
|
||||
async getServiceInfo(serviceName: string) {
|
||||
return this.executeOperation(
|
||||
() => this.coreApi.readNamespacedService({ name: serviceName, namespace: this.namespace }),
|
||||
`Failed to fetch service info for ${serviceName}`
|
||||
);
|
||||
}
|
||||
|
||||
async getServerConnectionInfo(serviceName: string) {
|
||||
return this.executeOperation(async () => {
|
||||
const service = await this.coreApi.readNamespacedService({
|
||||
name: serviceName,
|
||||
namespace: this.namespace,
|
||||
});
|
||||
|
||||
const serviceType = service.spec?.type || "ClusterIP";
|
||||
const ports = service.spec?.ports || [];
|
||||
|
||||
let host: string;
|
||||
let externalHost: string | undefined;
|
||||
|
||||
switch (serviceType) {
|
||||
case "LoadBalancer": {
|
||||
const ingress = service.status?.loadBalancer?.ingress?.[0];
|
||||
host =
|
||||
ingress?.hostname ||
|
||||
ingress?.ip ||
|
||||
`${serviceName}.${this.namespace}.svc.cluster.local`;
|
||||
externalHost = ingress?.hostname || ingress?.ip;
|
||||
break;
|
||||
}
|
||||
|
||||
case "NodePort":
|
||||
host = `${serviceName}.${this.namespace}.svc.cluster.local`;
|
||||
externalHost = "<node-ip>";
|
||||
break;
|
||||
|
||||
default:
|
||||
host = `${serviceName}.${this.namespace}.svc.cluster.local`;
|
||||
externalHost = undefined;
|
||||
}
|
||||
|
||||
const portMappings = ports.map((port) => ({
|
||||
name: port.name,
|
||||
port: port.port,
|
||||
targetPort: port.targetPort,
|
||||
nodePort: port.nodePort,
|
||||
protocol: port.protocol || "TCP",
|
||||
}));
|
||||
|
||||
return {
|
||||
serviceName,
|
||||
namespace: this.namespace,
|
||||
serviceType,
|
||||
internalHost: host,
|
||||
externalHost,
|
||||
ports: portMappings,
|
||||
};
|
||||
}, `Failed to fetch connection info for service ${serviceName}`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import type * as k8s from "@kubernetes/client-node";
|
||||
import { BaseK8sOperations } from "./base.operations";
|
||||
|
||||
export class PodOperations extends BaseK8sOperations {
|
||||
constructor(
|
||||
private coreApi: k8s.CoreV1Api,
|
||||
namespace: string
|
||||
) {
|
||||
super(namespace);
|
||||
}
|
||||
|
||||
async listPods() {
|
||||
return this.executeOperation(
|
||||
() => this.coreApi.listNamespacedPod({ namespace: this.namespace }).then((r) => r.items),
|
||||
"Failed to fetch pods"
|
||||
);
|
||||
}
|
||||
|
||||
async listPodsByLabel(labelSelector: string) {
|
||||
return this.executeOperation(
|
||||
() =>
|
||||
this.coreApi
|
||||
.listNamespacedPod({ namespace: this.namespace, labelSelector })
|
||||
.then((r) => r.items),
|
||||
"Failed to fetch pods by label"
|
||||
);
|
||||
}
|
||||
|
||||
async getPodInfo(podName: string) {
|
||||
return this.executeOperation(
|
||||
() => this.coreApi.readNamespacedPod({ name: podName, namespace: this.namespace }),
|
||||
`Failed to fetch pod info for ${podName}`
|
||||
);
|
||||
}
|
||||
|
||||
async getPodLogs(
|
||||
podName: string,
|
||||
options?: {
|
||||
container?: string;
|
||||
tailLines?: number;
|
||||
timestamps?: boolean;
|
||||
sinceSeconds?: number;
|
||||
}
|
||||
): Promise<string> {
|
||||
return this.executeOperation(
|
||||
() =>
|
||||
this.coreApi.readNamespacedPodLog({
|
||||
name: podName,
|
||||
namespace: this.namespace,
|
||||
container: options?.container,
|
||||
tailLines: options?.tailLines,
|
||||
timestamps: options?.timestamps,
|
||||
sinceSeconds: options?.sinceSeconds,
|
||||
}),
|
||||
`Failed to fetch logs for pod ${podName}`
|
||||
);
|
||||
}
|
||||
|
||||
async getPodMetrics(customObjectsApi: k8s.CustomObjectsApi, namespace?: string) {
|
||||
const ns = namespace || this.namespace;
|
||||
return this.executeOperation(
|
||||
() =>
|
||||
customObjectsApi.listNamespacedCustomObject({
|
||||
group: "metrics.k8s.io",
|
||||
version: "v1beta1",
|
||||
namespace: ns,
|
||||
plural: "pods",
|
||||
}),
|
||||
"Failed to fetch pod metrics"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import type * as k8s from "@kubernetes/client-node";
|
||||
import { BaseK8sOperations } from "./base.operations";
|
||||
|
||||
export class WorkloadOperations extends BaseK8sOperations {
|
||||
constructor(
|
||||
private appsApi: k8s.AppsV1Api,
|
||||
namespace: string
|
||||
) {
|
||||
super(namespace);
|
||||
}
|
||||
|
||||
async listDeployments() {
|
||||
return this.executeOperation(
|
||||
() =>
|
||||
this.appsApi.listNamespacedDeployment({ namespace: this.namespace }).then((r) => r.items),
|
||||
"Failed to fetch deployments"
|
||||
);
|
||||
}
|
||||
|
||||
async listStatefulSets() {
|
||||
return this.executeOperation(
|
||||
() =>
|
||||
this.appsApi.listNamespacedStatefulSet({ namespace: this.namespace }).then((r) => r.items),
|
||||
"Failed to fetch statefulsets"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import type {
|
||||
PodInfo,
|
||||
StatefulSetInfo,
|
||||
} from "@minikura/api";
|
||||
import { getAge } from "@minikura/shared/errors";
|
||||
|
||||
export class K8sResources {
|
||||
constructor(
|
||||
@@ -216,7 +217,9 @@ export class K8sResources {
|
||||
const internalIP = addresses.find((address) => address.type === "InternalIP")?.address;
|
||||
const externalIP = addresses.find((address) => address.type === "ExternalIP")?.address;
|
||||
const hostname = addresses.find((address) => address.type === "Hostname")?.address;
|
||||
const readyCondition = node.status?.conditions?.find((condition) => condition.type === "Ready");
|
||||
const readyCondition = node.status?.conditions?.find(
|
||||
(condition) => condition.type === "Ready"
|
||||
);
|
||||
|
||||
return {
|
||||
name: node.metadata?.name,
|
||||
@@ -252,20 +255,3 @@ function mapPodInfo(pod: k8s.V1Pod): PodInfo {
|
||||
nodeName: pod.spec?.nodeName,
|
||||
};
|
||||
}
|
||||
|
||||
function getAge(timestamp: Date | string | undefined): string {
|
||||
if (!timestamp) return "unknown";
|
||||
const now = new Date();
|
||||
const created = new Date(timestamp);
|
||||
const diff = now.getTime() - created.getTime();
|
||||
|
||||
const seconds = Math.floor(diff / 1000);
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
const hours = Math.floor(minutes / 60);
|
||||
const days = Math.floor(hours / 24);
|
||||
|
||||
if (days > 0) return `${days}d`;
|
||||
if (hours > 0) return `${hours}h`;
|
||||
if (minutes > 0) return `${minutes}m`;
|
||||
return `${seconds}s`;
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
import { logger } from "../infrastructure/logger";
|
||||
|
||||
export type WebSocketClient = {
|
||||
send: (message: string) => void;
|
||||
};
|
||||
@@ -14,14 +16,12 @@ export class WebSocketService implements IWebSocketService {
|
||||
|
||||
addClient(client: WebSocketClient): void {
|
||||
this.clients.add(client);
|
||||
console.log(`[WebSocket] Client connected (total: ${this.clients.size})`);
|
||||
logger.debug({ totalClients: this.clients.size }, "WebSocket client connected");
|
||||
}
|
||||
|
||||
removeClient(client: WebSocketClient): void {
|
||||
this.clients.delete(client);
|
||||
console.log(
|
||||
`[WebSocket] Client disconnected (total: ${this.clients.size})`,
|
||||
);
|
||||
logger.debug({ totalClients: this.clients.size }, "WebSocket client disconnected");
|
||||
}
|
||||
|
||||
broadcast(action: string, serverType: string, serverId: string): void {
|
||||
@@ -33,6 +33,7 @@ export class WebSocketService implements IWebSocketService {
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
|
||||
// Send to all connected clients, removing any that fail
|
||||
let failedClients = 0;
|
||||
this.clients.forEach((client) => {
|
||||
try {
|
||||
@@ -44,7 +45,7 @@ export class WebSocketService implements IWebSocketService {
|
||||
});
|
||||
|
||||
if (failedClients > 0) {
|
||||
console.log(`[WebSocket] Removed ${failedClients} failed clients`);
|
||||
logger.warn({ failedClients }, "Removed failed WebSocket clients");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user