mirror of
https://github.com/YuzuZensai/Minikura.git
synced 2026-03-30 09:22:31 +00:00
✨ feat: topology, and improves handling
This commit is contained in:
@@ -20,7 +20,7 @@ services:
|
||||
- "6443:6443" # k3s API
|
||||
- "25565:25565" # minecraft
|
||||
- "25577:25577" # velocity
|
||||
- "30000:32767" # NodePort range
|
||||
- "30000-32767:30000-32767" # NodePort range
|
||||
volumes:
|
||||
- "../:/workspace"
|
||||
- "/sys/fs/cgroup:/sys/fs/cgroup:rw"
|
||||
@@ -32,8 +32,9 @@ services:
|
||||
environment:
|
||||
- KUBECONFIG=/home/dev/.kube/config
|
||||
- DATABASE_URL=postgresql://postgres:postgres@db:5432/minikura?sslmode=disable
|
||||
- WEB_URL=http://localhost:3001
|
||||
- NEXT_PUBLIC_API_URL=http://localhost:3000
|
||||
- KUBERNETES_NAMESPACE=minikura
|
||||
- KUBERNETES_SKIP_TLS_VERIFY=true
|
||||
- ENABLE_CRD_REFLECTION=true
|
||||
|
||||
db:
|
||||
|
||||
@@ -25,20 +25,35 @@ mkdir -p /home/dev/.kube
|
||||
until [ -f /etc/rancher/k3s/k3s.yaml ]; do sleep 1; done
|
||||
sudo cp /etc/rancher/k3s/k3s.yaml /home/dev/.kube/config
|
||||
sudo chown dev:dev /home/dev/.kube/config
|
||||
chmod 600 /home/dev/.kube/config
|
||||
|
||||
# Wait for node
|
||||
echo "==> Waiting for node..."
|
||||
# Allow k3s self-signed certs
|
||||
kubectl config set-cluster default --insecure-skip-tls-verify=true
|
||||
|
||||
# Wait for k3s API server to be fully ready
|
||||
echo "==> Waiting for k3s API server..."
|
||||
for i in {1..60}; do
|
||||
kubectl get nodes --request-timeout=2s >/dev/null 2>&1 && break
|
||||
echo " Attempt $i/60..."
|
||||
sleep 1
|
||||
done
|
||||
sleep 2 # Extra buffer for stability
|
||||
|
||||
# Verify k3s is actually working
|
||||
echo "==> Verifying k3s..."
|
||||
kubectl get nodes || { echo "[ERROR] k3s not responding properly"; exit 1; }
|
||||
|
||||
# Wait for node to be Ready
|
||||
echo "==> Waiting for node to be Ready..."
|
||||
for i in {1..30}; do
|
||||
kubectl get nodes 2>/dev/null | grep -q " Ready" && break
|
||||
sleep 2
|
||||
done
|
||||
|
||||
# Create namespace
|
||||
echo "==> Creating minikura namespace..."
|
||||
kubectl create namespace minikura --dry-run=client -o yaml | kubectl apply -f - 2>/dev/null || true
|
||||
|
||||
# Uncomment the line below if you need service account token in .env
|
||||
# bash /workspace/.devcontainer/setup-k8s-token.sh
|
||||
|
||||
# Install dependencies
|
||||
echo "==> Installing dependencies..."
|
||||
cd /workspace
|
||||
|
||||
@@ -1,103 +0,0 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
NAMESPACE="minikura"
|
||||
SERVICE_ACCOUNT="minikura-backend"
|
||||
SECRET_NAME="minikura-backend-token"
|
||||
|
||||
echo "==> Setting up Kubernetes service account..."
|
||||
|
||||
# Create service account if it doesn't exist
|
||||
kubectl create serviceaccount $SERVICE_ACCOUNT -n $NAMESPACE --dry-run=client -o yaml | kubectl apply -f - 2>/dev/null || true
|
||||
|
||||
# Create RBAC role
|
||||
cat <<EOF | kubectl apply -f -
|
||||
apiVersion: rbac.authorization.k8s.io/v1
|
||||
kind: Role
|
||||
metadata:
|
||||
name: minikura-backend-role
|
||||
namespace: $NAMESPACE
|
||||
rules:
|
||||
- apiGroups: [""]
|
||||
resources: ["services", "pods", "pods/log"]
|
||||
verbs: ["get", "list", "watch"]
|
||||
- apiGroups: ["apps"]
|
||||
resources: ["deployments", "statefulsets"]
|
||||
verbs: ["get", "list", "watch"]
|
||||
- apiGroups: ["networking.k8s.io"]
|
||||
resources: ["ingresses"]
|
||||
verbs: ["get", "list", "watch"]
|
||||
- apiGroups: [""]
|
||||
resources: ["nodes"]
|
||||
verbs: ["get", "list"]
|
||||
EOF
|
||||
|
||||
# Create role binding
|
||||
cat <<EOF | kubectl apply -f -
|
||||
apiVersion: rbac.authorization.k8s.io/v1
|
||||
kind: RoleBinding
|
||||
metadata:
|
||||
name: minikura-backend-rolebinding
|
||||
namespace: $NAMESPACE
|
||||
subjects:
|
||||
- kind: ServiceAccount
|
||||
name: $SERVICE_ACCOUNT
|
||||
namespace: $NAMESPACE
|
||||
roleRef:
|
||||
kind: Role
|
||||
name: minikura-backend-role
|
||||
apiGroup: rbac.authorization.k8s.io
|
||||
EOF
|
||||
|
||||
# Create secret for service account token
|
||||
cat <<EOF | kubectl apply -f -
|
||||
apiVersion: v1
|
||||
kind: Secret
|
||||
metadata:
|
||||
name: $SECRET_NAME
|
||||
namespace: $NAMESPACE
|
||||
annotations:
|
||||
kubernetes.io/service-account.name: $SERVICE_ACCOUNT
|
||||
type: kubernetes.io/service-account-token
|
||||
EOF
|
||||
|
||||
echo "==> Waiting for token to be generated..."
|
||||
sleep 3
|
||||
|
||||
# Get the token
|
||||
TOKEN=$(kubectl get secret $SECRET_NAME -n $NAMESPACE -o jsonpath='{.data.token}' 2>/dev/null | base64 -d)
|
||||
|
||||
if [ -z "$TOKEN" ]; then
|
||||
echo "[ERROR] Failed to retrieve service account token"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "=============================================="
|
||||
echo "[OK] Service Account Token Retrieved"
|
||||
echo "=============================================="
|
||||
echo "Service Account: $SERVICE_ACCOUNT"
|
||||
echo "Namespace: $NAMESPACE"
|
||||
echo "Token: ${TOKEN:0:50}...${TOKEN: -20}"
|
||||
echo ""
|
||||
|
||||
# Update .env file with the new token
|
||||
ENV_FILE="/workspace/.env"
|
||||
|
||||
if [ -f "$ENV_FILE" ]; then
|
||||
# Check if token line exists
|
||||
if grep -q "^KUBERNETES_SERVICE_ACCOUNT_TOKEN=" "$ENV_FILE"; then
|
||||
# Update existing token
|
||||
sed -i "s|^KUBERNETES_SERVICE_ACCOUNT_TOKEN=.*|KUBERNETES_SERVICE_ACCOUNT_TOKEN=\"$TOKEN\"|" "$ENV_FILE"
|
||||
echo "[OK] Updated KUBERNETES_SERVICE_ACCOUNT_TOKEN in .env"
|
||||
else
|
||||
# Add token to end of file
|
||||
echo "KUBERNETES_SERVICE_ACCOUNT_TOKEN=\"$TOKEN\"" >> "$ENV_FILE"
|
||||
echo "[OK] Added KUBERNETES_SERVICE_ACCOUNT_TOKEN to .env"
|
||||
fi
|
||||
else
|
||||
echo "[WARNING] .env file not found at $ENV_FILE"
|
||||
fi
|
||||
|
||||
echo "=============================================="
|
||||
echo ""
|
||||
12
.env.example
12
.env.example
@@ -10,20 +10,8 @@ WEB_URL="http://localhost:3001"
|
||||
NEXT_PUBLIC_API_URL="http://localhost:3000"
|
||||
|
||||
# Kubernetes Configuration
|
||||
# The Kubernetes namespace where resources will be created
|
||||
KUBERNETES_NAMESPACE="minikura"
|
||||
|
||||
# Skip TLS certificate verification for Kubernetes API
|
||||
KUBERNETES_SKIP_TLS_VERIFY="true"
|
||||
|
||||
# Node.js TLS rejection control (needed when KUBERNETES_SKIP_TLS_VERIFY is true)
|
||||
NODE_TLS_REJECT_UNAUTHORIZED="0"
|
||||
|
||||
# Optional: Service account token for Kubernetes authentication
|
||||
# By default, uses ~/.kube/config (local development or in-cluster config)
|
||||
# Only set this for production deployments outside the cluster
|
||||
# KUBERNETES_SERVICE_ACCOUNT_TOKEN="your-token-here"
|
||||
|
||||
# Kubernetes Operator Configuration
|
||||
# Enable CRD reflection to automatically sync database state to Kubernetes Custom Resources
|
||||
# Set to "false" to disable automatic CRD creation from database entries
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,16 +4,10 @@ import { Loader2 } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { api } from "@/lib/api";
|
||||
import { api } from "@/lib/api-client";
|
||||
|
||||
export default function BootstrapPage() {
|
||||
const router = useRouter();
|
||||
@@ -29,8 +23,7 @@ export default function BootstrapPage() {
|
||||
if (data && !data.needsSetup) {
|
||||
router.replace("/login");
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Failed to check bootstrap status:", err);
|
||||
} catch (_err) {
|
||||
} finally {
|
||||
setCheckingStatus(false);
|
||||
}
|
||||
@@ -77,7 +70,7 @@ export default function BootstrapPage() {
|
||||
} else {
|
||||
setError("Failed to create admin user");
|
||||
}
|
||||
} catch (err) {
|
||||
} catch (_err) {
|
||||
setError("Failed to connect to server");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
@@ -96,9 +89,7 @@ export default function BootstrapPage() {
|
||||
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 to-slate-100 p-4">
|
||||
<Card className="w-full max-w-md">
|
||||
<CardHeader className="space-y-1">
|
||||
<CardTitle className="text-2xl font-bold text-center">
|
||||
Welcome to Minikura
|
||||
</CardTitle>
|
||||
<CardTitle className="text-2xl font-bold text-center">Welcome to Minikura</CardTitle>
|
||||
<CardDescription className="text-center">
|
||||
Create your admin account to get started
|
||||
</CardDescription>
|
||||
@@ -107,13 +98,7 @@ export default function BootstrapPage() {
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="name">Full Name</Label>
|
||||
<Input
|
||||
id="name"
|
||||
name="name"
|
||||
placeholder="John Doe"
|
||||
required
|
||||
autoFocus
|
||||
/>
|
||||
<Input id="name" name="name" placeholder="John Doe" required autoFocus />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="email">Email</Label>
|
||||
@@ -147,9 +132,7 @@ export default function BootstrapPage() {
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
{error && (
|
||||
<div className="text-sm text-red-600 text-center">{error}</div>
|
||||
)}
|
||||
{error && <div className="text-sm text-red-600 text-center">{error}</div>}
|
||||
<Button type="submit" className="w-full" disabled={loading}>
|
||||
{loading ? "Creating..." : "Create Admin Account"}
|
||||
</Button>
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
"use client";
|
||||
|
||||
import { AlertCircle, CheckCircle2, XCircle } from "lucide-react";
|
||||
import type {
|
||||
CustomResourceSummary,
|
||||
DeploymentInfo,
|
||||
@@ -10,6 +9,7 @@ import type {
|
||||
PodInfo,
|
||||
StatefulSetInfo,
|
||||
} from "@minikura/api";
|
||||
import { AlertCircle, CheckCircle2, XCircle } from "lucide-react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
@@ -23,7 +23,7 @@ import {
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { api } from "@/lib/api";
|
||||
import { api } from "@/lib/api-client";
|
||||
|
||||
export default function K8sResourcesPage() {
|
||||
const [status, setStatus] = useState<K8sStatus | null>(null);
|
||||
@@ -64,50 +64,34 @@ export default function K8sResourcesPage() {
|
||||
|
||||
if (statusRes.status === "fulfilled" && statusRes.value.data) {
|
||||
setStatus(statusRes.value.data as K8sStatus);
|
||||
} else if (statusRes.status === "rejected") {
|
||||
console.error("Failed to fetch status:", statusRes.reason);
|
||||
}
|
||||
|
||||
if (podsRes.status === "fulfilled" && podsRes.value.data) {
|
||||
setPods(podsRes.value.data as PodInfo[]);
|
||||
} else if (podsRes.status === "rejected") {
|
||||
console.error("Failed to fetch pods:", podsRes.reason);
|
||||
}
|
||||
|
||||
if (deploymentsRes.status === "fulfilled" && deploymentsRes.value.data) {
|
||||
setDeployments(deploymentsRes.value.data as DeploymentInfo[]);
|
||||
} else if (deploymentsRes.status === "rejected") {
|
||||
console.error("Failed to fetch deployments:", deploymentsRes.reason);
|
||||
}
|
||||
|
||||
if (statefulSetsRes.status === "fulfilled" && statefulSetsRes.value.data) {
|
||||
setStatefulSets(statefulSetsRes.value.data as StatefulSetInfo[]);
|
||||
} else if (statefulSetsRes.status === "rejected") {
|
||||
console.error("Failed to fetch statefulsets:", statefulSetsRes.reason);
|
||||
}
|
||||
|
||||
if (servicesRes.status === "fulfilled" && servicesRes.value.data) {
|
||||
setServices(servicesRes.value.data as K8sServiceSummary[]);
|
||||
} else if (servicesRes.status === "rejected") {
|
||||
console.error("Failed to fetch services:", servicesRes.reason);
|
||||
}
|
||||
|
||||
if (configMapsRes.status === "fulfilled" && configMapsRes.value.data) {
|
||||
setConfigMaps(configMapsRes.value.data as K8sConfigMapSummary[]);
|
||||
} else if (configMapsRes.status === "rejected") {
|
||||
console.error("Failed to fetch configmaps:", configMapsRes.reason);
|
||||
}
|
||||
|
||||
if (minecraftServersRes.status === "fulfilled" && minecraftServersRes.value.data) {
|
||||
setMinecraftServers(minecraftServersRes.value.data as CustomResourceSummary[]);
|
||||
} else if (minecraftServersRes.status === "rejected") {
|
||||
console.error("Failed to fetch minecraft servers:", minecraftServersRes.reason);
|
||||
}
|
||||
|
||||
if (reverseProxyServersRes.status === "fulfilled" && reverseProxyServersRes.value.data) {
|
||||
setReverseProxyServers(reverseProxyServersRes.value.data as CustomResourceSummary[]);
|
||||
} else if (reverseProxyServersRes.status === "rejected") {
|
||||
console.error("Failed to fetch reverse proxy servers:", reverseProxyServersRes.reason);
|
||||
}
|
||||
} catch (err: unknown) {
|
||||
const errorMessage =
|
||||
|
||||
@@ -6,7 +6,15 @@ import { useRouter } from "next/navigation";
|
||||
import { ServerForm, type ServerFormData } from "@/components/server-form";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { api } from "@/lib/api";
|
||||
import { api } from "@/lib/api-client";
|
||||
|
||||
const toDifficultyUppercase = (value: string): "PEACEFUL" | "EASY" | "NORMAL" | "HARD" => {
|
||||
return value.toUpperCase() as "PEACEFUL" | "EASY" | "NORMAL" | "HARD";
|
||||
};
|
||||
|
||||
const toModeUppercase = (value: string): "SURVIVAL" | "CREATIVE" | "ADVENTURE" | "SPECTATOR" => {
|
||||
return value.toUpperCase() as "SURVIVAL" | "CREATIVE" | "ADVENTURE" | "SPECTATOR";
|
||||
};
|
||||
|
||||
export default function CreateServerPage() {
|
||||
const router = useRouter();
|
||||
@@ -121,8 +129,8 @@ export default function CreateServerPage() {
|
||||
jvm_opts: data.jvmOpts || undefined,
|
||||
use_aikar_flags: data.useAikarFlags || undefined,
|
||||
use_meowice_flags: data.useMeowiceFlags || undefined,
|
||||
difficulty: data.difficulty,
|
||||
game_mode: data.mode,
|
||||
difficulty: toDifficultyUppercase(data.difficulty),
|
||||
game_mode: toModeUppercase(data.mode),
|
||||
max_players: data.maxPlayers ? Number(data.maxPlayers) : undefined,
|
||||
pvp: data.pvp,
|
||||
online_mode: data.onlineMode,
|
||||
|
||||
@@ -7,7 +7,7 @@ import { useEffect, useState } from "react";
|
||||
import { ServerForm, type ServerFormData, type ServerType } from "@/components/server-form";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { api } from "@/lib/api";
|
||||
import { api } from "@/lib/api-client";
|
||||
import { getReverseProxyApi } from "@/lib/api-helpers";
|
||||
|
||||
export default function EditServerPage() {
|
||||
@@ -48,8 +48,7 @@ export default function EditServerPage() {
|
||||
|
||||
setError("Server not found");
|
||||
setLoading(false);
|
||||
} catch (err) {
|
||||
console.error("Failed to fetch server:", err);
|
||||
} catch (_err) {
|
||||
setError("Failed to load server data");
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -81,11 +80,12 @@ export default function EditServerPage() {
|
||||
return "survival";
|
||||
};
|
||||
|
||||
const toServerType = (value?: string | null): ServerType => {
|
||||
if (value === "VANILLA" || value === "CUSTOM") {
|
||||
return value;
|
||||
}
|
||||
return "PAPER";
|
||||
const toDifficultyUppercase = (value: string): "PEACEFUL" | "EASY" | "NORMAL" | "HARD" => {
|
||||
return value.toUpperCase() as "PEACEFUL" | "EASY" | "NORMAL" | "HARD";
|
||||
};
|
||||
|
||||
const toModeUppercase = (value: string): "SURVIVAL" | "CREATIVE" | "ADVENTURE" | "SPECTATOR" => {
|
||||
return value.toUpperCase() as "SURVIVAL" | "CREATIVE" | "ADVENTURE" | "SPECTATOR";
|
||||
};
|
||||
|
||||
const parseEnvVariables = (envVars?: Array<{ key: string; value: string }>) => {
|
||||
@@ -205,8 +205,8 @@ export default function EditServerPage() {
|
||||
jvm_opts: data.jvmOpts || undefined,
|
||||
use_aikar_flags: data.useAikarFlags || undefined,
|
||||
use_meowice_flags: data.useMeowiceFlags || undefined,
|
||||
difficulty: data.difficulty,
|
||||
game_mode: data.mode,
|
||||
difficulty: toDifficultyUppercase(data.difficulty),
|
||||
game_mode: toModeUppercase(data.mode),
|
||||
max_players: data.maxPlayers ? Number(data.maxPlayers) : undefined,
|
||||
pvp: data.pvp,
|
||||
online_mode: data.onlineMode,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import type { ConnectionInfo, NormalServer, PodInfo, ReverseProxyServer } from "@minikura/api";
|
||||
import {
|
||||
AlertCircle,
|
||||
Check,
|
||||
@@ -25,15 +26,6 @@ import {
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
@@ -42,14 +34,10 @@ import {
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import type { ConnectionInfo, NormalServer, PodInfo, ReverseProxyServer } from "@minikura/api";
|
||||
import { api } from "@/lib/api-client";
|
||||
import { getReverseProxyApi } from "@/lib/api-helpers";
|
||||
import { api } from "@/lib/api";
|
||||
|
||||
// Server status component
|
||||
function ServerStatusCell({ serverId, type }: { serverId: string; type: "normal" | "proxy" }) {
|
||||
const [pods, setPods] = useState<PodInfo[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
@@ -59,14 +47,13 @@ function ServerStatusCell({ serverId, type }: { serverId: string; type: "normal"
|
||||
try {
|
||||
const endpoint =
|
||||
type === "normal"
|
||||
? api.api.k8s["servers"]({ serverId }).pods.get
|
||||
? api.api.k8s.servers({ serverId }).pods.get
|
||||
: api.api.k8s["reverse-proxy"]({ serverId }).pods.get;
|
||||
const res = await endpoint();
|
||||
if (res.data) {
|
||||
setPods(res.data as PodInfo[]);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch pods:", error);
|
||||
} catch (_error) {
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -93,9 +80,7 @@ function ServerStatusCell({ serverId, type }: { serverId: string; type: "normal"
|
||||
}
|
||||
|
||||
const allRunning = pods.every((pod) => pod.status === "Running");
|
||||
const readyCount = pods.filter(
|
||||
(pod) => pod.ready === "1/1" || pod.ready === "1/1" || pod.ready === "1/1"
|
||||
).length;
|
||||
const readyCount = pods.filter((pod) => pod.ready === "1/1").length;
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
@@ -111,7 +96,6 @@ function ServerStatusCell({ serverId, type }: { serverId: string; type: "normal"
|
||||
);
|
||||
}
|
||||
|
||||
// Connection info component
|
||||
function ConnectionInfoCell({ serverId, type }: { serverId: string; type: "normal" | "proxy" }) {
|
||||
const [connectionInfo, setConnectionInfo] = useState<ConnectionInfo | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
@@ -129,8 +113,7 @@ function ConnectionInfoCell({ serverId, type }: { serverId: string; type: "norma
|
||||
if (res.data) {
|
||||
setConnectionInfo(res.data as ConnectionInfo);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch connection info:", error);
|
||||
} catch (_error) {
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -213,8 +196,7 @@ export default function ServersPage() {
|
||||
if (proxyRes.data) {
|
||||
setReverseProxies(proxyRes.data as unknown as ReverseProxyServer[]);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch servers:", error);
|
||||
} catch (_error) {
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -236,9 +218,7 @@ export default function ServersPage() {
|
||||
}
|
||||
await fetchServers();
|
||||
setDeleteTarget(null);
|
||||
} catch (error) {
|
||||
console.error("Failed to delete server:", error);
|
||||
}
|
||||
} catch (_error) {}
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
@@ -270,7 +250,6 @@ export default function ServersPage() {
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Normal Servers */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center gap-2">
|
||||
@@ -360,7 +339,6 @@ export default function ServersPage() {
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Reverse Proxy Servers */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center gap-2">
|
||||
@@ -448,7 +426,6 @@ export default function ServersPage() {
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Delete Confirmation Dialog */}
|
||||
<Dialog open={!!deleteTarget} onOpenChange={() => setDeleteTarget(null)}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
|
||||
89
apps/web/app/dashboard/topology/page.tsx
Normal file
89
apps/web/app/dashboard/topology/page.tsx
Normal file
@@ -0,0 +1,89 @@
|
||||
"use client";
|
||||
|
||||
import { Network, RefreshCw } from "lucide-react";
|
||||
import { TopologyCanvas } from "@/components/topology/topology-canvas";
|
||||
import { useTopologyData } from "@/hooks/use-topology-data";
|
||||
|
||||
export default function TopologyPage() {
|
||||
const { graph, loading, error } = useTopologyData();
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold">Network Topology</h1>
|
||||
<p className="text-muted-foreground mt-1">
|
||||
Real-time server infrastructure, proxy connections, and Kubernetes nodes
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center justify-center h-[calc(100vh-250px)]">
|
||||
<div className="flex flex-col items-center gap-2">
|
||||
<RefreshCw className="h-8 w-8 animate-spin text-muted-foreground" />
|
||||
<p className="text-muted-foreground">Loading topology...</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold">Network Topology</h1>
|
||||
<p className="text-muted-foreground mt-1">
|
||||
Real-time server infrastructure, proxy connections, and Kubernetes nodes
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center justify-center h-[calc(100vh-250px)] border-2 border-dashed rounded-lg">
|
||||
<div className="flex flex-col items-center gap-2 p-6 text-center">
|
||||
<p className="text-destructive font-semibold">Error loading topology</p>
|
||||
<p className="text-muted-foreground text-sm">{error}</p>
|
||||
<p className="text-muted-foreground text-xs mt-2">Auto-retrying...</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!graph || graph.nodes.length === 0) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold">Network Topology</h1>
|
||||
<p className="text-muted-foreground mt-1">
|
||||
Real-time server infrastructure, proxy connections, and Kubernetes nodes
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center justify-center h-[calc(100vh-250px)] border-2 border-dashed rounded-lg">
|
||||
<div className="flex flex-col items-center gap-2 p-6 text-center">
|
||||
<p className="text-muted-foreground">No servers or infrastructure found</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Create a server to see it appear in the topology
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="p-2 bg-primary/10 rounded-lg">
|
||||
<Network className="h-6 w-6 text-primary" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold">Network Topology</h1>
|
||||
<p className="text-muted-foreground mt-1">
|
||||
Real-time server infrastructure, proxy connections, and Kubernetes nodes
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<TopologyCanvas graph={graph} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
import { Ban, CheckCircle, Edit, Trash2 } from "lucide-react";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { getUserApi } from "@/lib/api-helpers";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
@@ -31,7 +30,8 @@ import {
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import { api } from "@/lib/api";
|
||||
import { api } from "@/lib/api-client";
|
||||
import { getUserApi } from "@/lib/api-helpers";
|
||||
import { useSession } from "@/lib/auth-client";
|
||||
|
||||
type User = {
|
||||
@@ -59,8 +59,7 @@ export default function UsersPage() {
|
||||
if (data && typeof data === "object" && "users" in data) {
|
||||
setUsers(data.users as User[]);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch users:", error);
|
||||
} catch (_error) {
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -88,9 +87,7 @@ export default function UsersPage() {
|
||||
await fetchUsers();
|
||||
setEditingUser(null);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to update user:", error);
|
||||
}
|
||||
} catch (_error) {}
|
||||
};
|
||||
|
||||
const handleSuspend = async (e: React.FormEvent<HTMLFormElement>) => {
|
||||
@@ -110,9 +107,7 @@ export default function UsersPage() {
|
||||
await fetchUsers();
|
||||
setSuspendingUser(null);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to suspend user:", error);
|
||||
}
|
||||
} catch (_error) {}
|
||||
};
|
||||
|
||||
const handleUnsuspend = async (userId: string) => {
|
||||
@@ -125,9 +120,7 @@ export default function UsersPage() {
|
||||
if (!error) {
|
||||
await fetchUsers();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to unsuspend user:", error);
|
||||
}
|
||||
} catch (_error) {}
|
||||
};
|
||||
|
||||
const handleDelete = async () => {
|
||||
@@ -140,9 +133,7 @@ export default function UsersPage() {
|
||||
await fetchUsers();
|
||||
setDeleteUser(null);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to delete user:", error);
|
||||
}
|
||||
} catch (_error) {}
|
||||
};
|
||||
|
||||
const isUserSuspended = (user: User): boolean => {
|
||||
@@ -252,7 +243,6 @@ export default function UsersPage() {
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Edit Dialog */}
|
||||
<Dialog open={!!editingUser} onOpenChange={() => setEditingUser(null)}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
@@ -288,7 +278,6 @@ export default function UsersPage() {
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Suspend Dialog */}
|
||||
<Dialog open={!!suspendingUser} onOpenChange={() => setSuspendingUser(null)}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
@@ -324,7 +313,6 @@ export default function UsersPage() {
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Delete Dialog */}
|
||||
<Dialog open={!!deleteUser} onOpenChange={() => setDeleteUser(null)}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
|
||||
@@ -41,7 +41,7 @@ export default function LoginPage() {
|
||||
} else {
|
||||
router.push("/dashboard");
|
||||
}
|
||||
} catch (err) {
|
||||
} catch (_err) {
|
||||
setError("Failed to connect to server");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
|
||||
@@ -1,13 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
Loader2,
|
||||
LogOut,
|
||||
Network,
|
||||
Server,
|
||||
Settings,
|
||||
Users,
|
||||
} from "lucide-react";
|
||||
import { GitGraph, Loader2, LogOut, Network, Server, Settings, Users } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { usePathname, useRouter } from "next/navigation";
|
||||
import { useEffect } from "react";
|
||||
@@ -39,11 +32,10 @@ import { signOut, useSession } from "@/lib/auth-client";
|
||||
const menuItems = [
|
||||
{ href: "/dashboard/users", icon: Users, label: "Users" },
|
||||
{ href: "/dashboard/servers", icon: Server, label: "Servers" },
|
||||
{ href: "/dashboard/topology", icon: GitGraph, label: "Network" },
|
||||
];
|
||||
|
||||
const k8sMenuItems = [
|
||||
{ href: "/dashboard/k8s", icon: Network, label: "Resources" },
|
||||
];
|
||||
const k8sMenuItems = [{ href: "/dashboard/k8s", icon: Network, label: "Resources" }];
|
||||
|
||||
export function DashboardLayout({ children }: { children: React.ReactNode }) {
|
||||
const pathname = usePathname();
|
||||
@@ -96,10 +88,7 @@ export function DashboardLayout({ children }: { children: React.ReactNode }) {
|
||||
<SidebarMenu>
|
||||
{menuItems.map((item) => (
|
||||
<SidebarMenuItem key={item.href}>
|
||||
<SidebarMenuButton
|
||||
asChild
|
||||
isActive={pathname === item.href}
|
||||
>
|
||||
<SidebarMenuButton asChild isActive={pathname === item.href}>
|
||||
<Link href={item.href}>
|
||||
<item.icon className="h-4 w-4" />
|
||||
<span>{item.label}</span>
|
||||
@@ -116,10 +105,7 @@ export function DashboardLayout({ children }: { children: React.ReactNode }) {
|
||||
<SidebarMenu>
|
||||
{k8sMenuItems.map((item) => (
|
||||
<SidebarMenuItem key={item.href}>
|
||||
<SidebarMenuButton
|
||||
asChild
|
||||
isActive={pathname === item.href}
|
||||
>
|
||||
<SidebarMenuButton asChild isActive={pathname === item.href}>
|
||||
<Link href={item.href}>
|
||||
<item.icon className="h-4 w-4" />
|
||||
<span>{item.label}</span>
|
||||
@@ -134,18 +120,13 @@ export function DashboardLayout({ children }: { children: React.ReactNode }) {
|
||||
<div className="border-t p-4">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="w-full justify-start gap-2 px-2"
|
||||
>
|
||||
<Button variant="ghost" className="w-full justify-start gap-2 px-2">
|
||||
<Avatar className="h-8 w-8">
|
||||
<AvatarFallback>{userInitials}</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="flex flex-col items-start text-sm">
|
||||
<span className="font-medium">{session?.user?.name}</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{session?.user?.email}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground">{session?.user?.email}</span>
|
||||
</div>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
|
||||
@@ -50,8 +50,7 @@ export function Terminal({
|
||||
const term = new XTerm({
|
||||
cursorBlink: true,
|
||||
fontSize: 14,
|
||||
fontFamily:
|
||||
'JetBrains Mono, Fira Code, Menlo, Monaco, "Courier New", monospace',
|
||||
fontFamily: 'JetBrains Mono, Fira Code, Menlo, Monaco, "Courier New", monospace',
|
||||
fontWeight: "normal",
|
||||
fontWeightBold: "bold",
|
||||
letterSpacing: 0,
|
||||
@@ -106,9 +105,7 @@ export function Terminal({
|
||||
try {
|
||||
const ligaturesAddon = new LigaturesAddon();
|
||||
term.loadAddon(ligaturesAddon);
|
||||
} catch (e) {
|
||||
console.warn("Ligatures addon not available:", e);
|
||||
}
|
||||
} catch (_e) {}
|
||||
|
||||
fitAddon.fit();
|
||||
|
||||
@@ -120,10 +117,7 @@ export function Terminal({
|
||||
try {
|
||||
const webglAddon = new WebglAddon();
|
||||
term.loadAddon(webglAddon);
|
||||
console.log("WebGL renderer loaded successfully");
|
||||
} catch (e) {
|
||||
console.warn("WebGL renderer not available, using canvas fallback:", e);
|
||||
}
|
||||
} catch (_e) {}
|
||||
}, 100);
|
||||
|
||||
term.attachCustomKeyEventHandler((event) => {
|
||||
@@ -141,10 +135,9 @@ export function Terminal({
|
||||
wsRef.current = ws;
|
||||
|
||||
ws.onopen = () => {
|
||||
console.log("WebSocket connected");
|
||||
setConnected(true);
|
||||
term.writeln(
|
||||
`\r\n\x1b[1;32mConnecting to ${mode === "attach" ? "container" : "shell"}...\x1b[0m\r\n`,
|
||||
`\r\n\x1b[1;32mConnecting to ${mode === "attach" ? "container" : "shell"}...\x1b[0m\r\n`
|
||||
);
|
||||
|
||||
const { cols, rows } = term;
|
||||
@@ -166,20 +159,16 @@ export function Terminal({
|
||||
term.writeln(`\r\n\x1b[1;33m${message.data}\x1b[0m\r\n`);
|
||||
setConnected(false);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Error parsing WebSocket message:", err);
|
||||
}
|
||||
} catch (_err) {}
|
||||
};
|
||||
|
||||
ws.onerror = (err) => {
|
||||
console.error("WebSocket error:", err);
|
||||
ws.onerror = (_err) => {
|
||||
term.writeln("\r\n\x1b[1;31mWebSocket error\x1b[0m\r\n");
|
||||
setError("Connection error");
|
||||
setConnected(false);
|
||||
};
|
||||
|
||||
ws.onclose = () => {
|
||||
console.log("WebSocket closed");
|
||||
term.writeln("\r\n\x1b[1;33mConnection closed\x1b[0m\r\n");
|
||||
setConnected(false);
|
||||
};
|
||||
@@ -220,9 +209,7 @@ export function Terminal({
|
||||
</div>
|
||||
)}
|
||||
{error && (
|
||||
<div className="bg-red-500/20 text-red-500 text-xs px-2 py-1 rounded">
|
||||
{error}
|
||||
</div>
|
||||
<div className="bg-red-500/20 text-red-500 text-xs px-2 py-1 rounded">{error}</div>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
|
||||
341
apps/web/components/topology/controls/node-details-panel.tsx
Normal file
341
apps/web/components/topology/controls/node-details-panel.tsx
Normal file
@@ -0,0 +1,341 @@
|
||||
"use client";
|
||||
|
||||
import { Box } from "lucide-react";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
} from "@/components/ui/sheet";
|
||||
import type {
|
||||
K8sNodeMetadata,
|
||||
ProxyMetadata,
|
||||
ServerMetadata,
|
||||
TopologyNodeData,
|
||||
} from "@/lib/topology-types";
|
||||
|
||||
interface NodeDetailsPanelProps {
|
||||
node: TopologyNodeData | null;
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export function NodeDetailsPanel({
|
||||
node,
|
||||
open,
|
||||
onClose,
|
||||
}: NodeDetailsPanelProps) {
|
||||
if (!node) return null;
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={onClose}>
|
||||
<SheetContent className="w-full sm:w-[600px] lg:w-[700px] overflow-y-auto p-6">
|
||||
<SheetHeader className="mb-6">
|
||||
<SheetTitle>{node.label}</SheetTitle>
|
||||
</SheetHeader>
|
||||
|
||||
<div className="space-y-4 pr-2">
|
||||
{/* Type and Status */}
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant="outline">
|
||||
{node.type === "server"
|
||||
? "Minecraft Server"
|
||||
: node.type === "proxy"
|
||||
? "Reverse Proxy"
|
||||
: "Kubernetes Node"}
|
||||
</Badge>
|
||||
<Badge
|
||||
variant={
|
||||
node.status === "healthy"
|
||||
? "default"
|
||||
: node.status === "degraded"
|
||||
? "secondary"
|
||||
: "destructive"
|
||||
}
|
||||
>
|
||||
{node.status}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{node.type === "server" && (
|
||||
<ServerDetails metadata={node.metadata as ServerMetadata} />
|
||||
)}
|
||||
{node.type === "proxy" && (
|
||||
<ProxyDetails metadata={node.metadata as ProxyMetadata} />
|
||||
)}
|
||||
{node.type === "k8s-node" && (
|
||||
<K8sNodeDetails metadata={node.metadata as K8sNodeMetadata} />
|
||||
)}
|
||||
</div>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
|
||||
function ServerDetails({ metadata }: { metadata: ServerMetadata }) {
|
||||
const { server, podCount, readyPods, pods, k8sNodes, connectedProxies } =
|
||||
metadata;
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<DetailSection title="Server Configuration">
|
||||
<DetailItem label="ID" value={server.id} />
|
||||
{server.description && (
|
||||
<DetailItem label="Description" value={server.description} />
|
||||
)}
|
||||
<DetailItem label="Type" value={server.type} />
|
||||
<DetailItem label="Jar Type" value={server.jar_type} />
|
||||
<DetailItem
|
||||
label="Minecraft Version"
|
||||
value={server.minecraft_version}
|
||||
/>
|
||||
<DetailItem label="Port" value={server.listen_port.toString()} />
|
||||
</DetailSection>
|
||||
|
||||
<DetailSection title="Kubernetes Info">
|
||||
<DetailItem label="Pods" value={`${readyPods}/${podCount} Ready`} />
|
||||
{k8sNodes.length > 0 && (
|
||||
<div className="space-y-1">
|
||||
<div className="flex items-center gap-2 text-sm mb-2">
|
||||
<Box className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="text-muted-foreground">
|
||||
Running on {k8sNodes.length} K8s node(s):
|
||||
</span>
|
||||
</div>
|
||||
{k8sNodes.map((nodeName) => (
|
||||
<div
|
||||
key={nodeName}
|
||||
className="text-sm p-2 bg-blue-50 border border-blue-200 rounded ml-6"
|
||||
>
|
||||
<span className="font-mono text-xs break-all">{nodeName}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{pods.map((pod) => (
|
||||
<div key={pod.name} className="text-sm mt-2 p-2 bg-muted rounded">
|
||||
<div className="font-medium font-mono text-xs break-all">
|
||||
{pod.name}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground space-y-0.5 mt-1">
|
||||
<div>
|
||||
Status: {pod.status} • {pod.ready}
|
||||
</div>
|
||||
<div>Restarts: {pod.restarts}</div>
|
||||
{pod.nodeName && (
|
||||
<div className="flex items-center gap-1">
|
||||
<Box className="h-3 w-3 shrink-0" />
|
||||
<span className="break-all">Node: {pod.nodeName}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</DetailSection>
|
||||
|
||||
{connectedProxies.length > 0 && (
|
||||
<DetailSection title="Proxy Connections">
|
||||
<DetailItem
|
||||
label="Behind Proxies"
|
||||
value={connectedProxies.length.toString()}
|
||||
/>
|
||||
<div className="mt-2 space-y-1">
|
||||
{connectedProxies.map((proxyId) => (
|
||||
<div
|
||||
key={proxyId}
|
||||
className="text-sm p-2 bg-blue-50 border border-blue-200 rounded font-mono break-all"
|
||||
>
|
||||
{proxyId}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</DetailSection>
|
||||
)}
|
||||
|
||||
<DetailSection title="Resources">
|
||||
<DetailItem
|
||||
label="Memory"
|
||||
value={`${server.memory_request}MB / ${server.memory}MB`}
|
||||
/>
|
||||
<DetailItem
|
||||
label="CPU Request"
|
||||
value={server.cpu_request || "Not set"}
|
||||
/>
|
||||
<DetailItem label="CPU Limit" value={server.cpu_limit || "Not set"} />
|
||||
</DetailSection>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ProxyDetails({ metadata }: { metadata: ProxyMetadata }) {
|
||||
const { proxy, podCount, readyPods, pods, k8sNodes, connectedServers } =
|
||||
metadata;
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<DetailSection title="Proxy Configuration">
|
||||
<DetailItem label="ID" value={proxy.id} />
|
||||
{proxy.description && (
|
||||
<DetailItem label="Description" value={proxy.description} />
|
||||
)}
|
||||
<DetailItem label="Type" value={proxy.type} />
|
||||
<DetailItem
|
||||
label="External Address"
|
||||
value={`${proxy.external_address}:${proxy.external_port}`}
|
||||
/>
|
||||
<DetailItem label="Listen Port" value={proxy.listen_port.toString()} />
|
||||
</DetailSection>
|
||||
|
||||
<DetailSection title="Kubernetes Info">
|
||||
<DetailItem label="Pods" value={`${readyPods}/${podCount} Ready`} />
|
||||
{k8sNodes.length > 0 && (
|
||||
<div className="space-y-1">
|
||||
<div className="flex items-center gap-2 text-sm mb-2">
|
||||
<Box className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="text-muted-foreground">
|
||||
Running on {k8sNodes.length} K8s node(s):
|
||||
</span>
|
||||
</div>
|
||||
{k8sNodes.map((nodeName) => (
|
||||
<div
|
||||
key={nodeName}
|
||||
className="text-sm p-2 bg-blue-50 border border-blue-200 rounded ml-6"
|
||||
>
|
||||
<span className="font-mono text-xs break-all">{nodeName}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{pods.map((pod) => (
|
||||
<div key={pod.name} className="text-sm mt-2 p-2 bg-muted rounded">
|
||||
<div className="font-medium font-mono text-xs break-all">
|
||||
{pod.name}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground space-y-0.5 mt-1">
|
||||
<div>
|
||||
Status: {pod.status} • {pod.ready}
|
||||
</div>
|
||||
<div>Restarts: {pod.restarts}</div>
|
||||
{pod.nodeName && (
|
||||
<div className="flex items-center gap-1">
|
||||
<Box className="h-3 w-3 shrink-0" />
|
||||
<span className="break-all">Node: {pod.nodeName}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</DetailSection>
|
||||
|
||||
<DetailSection title="Connected Servers">
|
||||
<DetailItem label="Total" value={connectedServers.length.toString()} />
|
||||
{connectedServers.length > 0 && (
|
||||
<div className="mt-2 space-y-1">
|
||||
{connectedServers.map((serverId) => (
|
||||
<div
|
||||
key={serverId}
|
||||
className="text-sm p-2 bg-green-50 border border-green-200 rounded font-mono break-all"
|
||||
>
|
||||
{serverId}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</DetailSection>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function K8sNodeDetails({ metadata }: { metadata: K8sNodeMetadata }) {
|
||||
const { node, podCount, serverPods, proxyPods } = metadata;
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<DetailSection title="Node Information">
|
||||
<DetailItem label="Name" value={node.name || "Unknown"} />
|
||||
<DetailItem label="Status" value={node.status} />
|
||||
{node.version && <DetailItem label="Version" value={node.version} />}
|
||||
{node.internalIP && (
|
||||
<DetailItem label="Internal IP" value={node.internalIP} />
|
||||
)}
|
||||
{node.externalIP && (
|
||||
<DetailItem label="External IP" value={node.externalIP} />
|
||||
)}
|
||||
</DetailSection>
|
||||
|
||||
<DetailSection title="Node Details">
|
||||
<DetailItem label="Roles" value={node.roles} />
|
||||
<DetailItem label="Age" value={node.age} />
|
||||
{node.hostname && <DetailItem label="Hostname" value={node.hostname} />}
|
||||
</DetailSection>
|
||||
|
||||
<DetailSection title="Running Pods">
|
||||
<DetailItem label="Total Pods" value={podCount.toString()} />
|
||||
<DetailItem label="Server Pods" value={serverPods.length.toString()} />
|
||||
<DetailItem label="Proxy Pods" value={proxyPods.length.toString()} />
|
||||
|
||||
{serverPods.length > 0 && (
|
||||
<div className="mt-3">
|
||||
<p className="text-sm font-medium mb-2">Server Pods:</p>
|
||||
<div className="space-y-1">
|
||||
{serverPods.map((podName) => (
|
||||
<div
|
||||
key={podName}
|
||||
className="text-xs p-2 bg-green-50 border border-green-200 rounded font-mono break-all"
|
||||
>
|
||||
{podName}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{proxyPods.length > 0 && (
|
||||
<div className="mt-3">
|
||||
<p className="text-sm font-medium mb-2">Proxy Pods:</p>
|
||||
<div className="space-y-1">
|
||||
{proxyPods.map((podName) => (
|
||||
<div
|
||||
key={podName}
|
||||
className="text-xs p-2 bg-blue-50 border border-blue-200 rounded font-mono break-all"
|
||||
>
|
||||
{podName}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</DetailSection>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function DetailSection({
|
||||
title,
|
||||
children,
|
||||
}: {
|
||||
title: string;
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<h3 className="font-semibold text-sm">{title}</h3>
|
||||
<div className="space-y-2">{children}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function DetailItem({ label, value }: { label: string; value: string }) {
|
||||
return (
|
||||
<div className="flex justify-between items-start text-sm gap-4">
|
||||
<span className="text-muted-foreground shrink-0">{label}:</span>
|
||||
<span className="font-medium text-right break-words">{value}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
159
apps/web/components/topology/controls/topology-toolbar.tsx
Normal file
159
apps/web/components/topology/controls/topology-toolbar.tsx
Normal file
@@ -0,0 +1,159 @@
|
||||
"use client";
|
||||
|
||||
import { Box, Filter, Globe, Search, Server } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import type { TopologyFilters } from "@/lib/topology-types";
|
||||
|
||||
interface TopologyToolbarProps {
|
||||
filters: TopologyFilters;
|
||||
onFiltersChange: (filters: TopologyFilters) => void;
|
||||
metadata: {
|
||||
totalServers: number;
|
||||
totalProxies: number;
|
||||
totalK8sNodes: number;
|
||||
totalConnections: number;
|
||||
healthySystems: number;
|
||||
degradedSystems: number;
|
||||
unhealthySystems: number;
|
||||
};
|
||||
}
|
||||
|
||||
export function TopologyToolbar({ filters, onFiltersChange, metadata }: TopologyToolbarProps) {
|
||||
const [searchQuery, setSearchQuery] = useState(filters.searchQuery);
|
||||
|
||||
const handleSearchChange = (value: string) => {
|
||||
setSearchQuery(value);
|
||||
onFiltersChange({ ...filters, searchQuery: value });
|
||||
};
|
||||
|
||||
const toggleFilter = (key: keyof TopologyFilters) => {
|
||||
onFiltersChange({ ...filters, [key]: !filters[key] });
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-3 p-4 bg-white/90 backdrop-blur-sm rounded-lg border shadow-lg min-w-[350px]">
|
||||
{/* Stats */}
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
<div className="flex flex-col items-center p-2 bg-muted/50 rounded">
|
||||
<div className="flex items-center gap-1 text-muted-foreground mb-1">
|
||||
<Server className="h-3 w-3" />
|
||||
<span className="text-xs">Servers</span>
|
||||
</div>
|
||||
<span className="text-lg font-bold">{metadata.totalServers}</span>
|
||||
</div>
|
||||
<div className="flex flex-col items-center p-2 bg-muted/50 rounded">
|
||||
<div className="flex items-center gap-1 text-muted-foreground mb-1">
|
||||
<Globe className="h-3 w-3" />
|
||||
<span className="text-xs">Proxies</span>
|
||||
</div>
|
||||
<span className="text-lg font-bold">{metadata.totalProxies}</span>
|
||||
</div>
|
||||
<div className="flex flex-col items-center p-2 bg-muted/50 rounded">
|
||||
<div className="flex items-center gap-1 text-muted-foreground mb-1">
|
||||
<Box className="h-3 w-3" />
|
||||
<span className="text-xs">Nodes</span>
|
||||
</div>
|
||||
<span className="text-lg font-bold">{metadata.totalK8sNodes}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Health Status */}
|
||||
<div className="flex gap-2 justify-between text-xs">
|
||||
<Badge variant="outline" className="flex items-center gap-1">
|
||||
<div className="w-2 h-2 rounded-full bg-green-500" />
|
||||
{metadata.healthySystems} Healthy
|
||||
</Badge>
|
||||
<Badge variant="outline" className="flex items-center gap-1">
|
||||
<div className="w-2 h-2 rounded-full bg-yellow-500" />
|
||||
{metadata.degradedSystems} Degraded
|
||||
</Badge>
|
||||
<Badge variant="outline" className="flex items-center gap-1">
|
||||
<div className="w-2 h-2 rounded-full bg-red-500" />
|
||||
{metadata.unhealthySystems} Down
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
{/* Search */}
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search..."
|
||||
value={searchQuery}
|
||||
onChange={(e) => handleSearchChange(e.target.value)}
|
||||
className="pl-9"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Filters */}
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<Button variant="outline" size="sm" className="w-full">
|
||||
<Filter className="h-4 w-4 mr-2" />
|
||||
Filters
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-80" align="start">
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<h4 className="font-semibold mb-3">Show/Hide</h4>
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label htmlFor="show-servers" className="flex items-center gap-2 cursor-pointer">
|
||||
<Server className="h-4 w-4" />
|
||||
<span>Servers</span>
|
||||
</Label>
|
||||
<Switch
|
||||
id="show-servers"
|
||||
checked={filters.showServers}
|
||||
onCheckedChange={() => toggleFilter("showServers")}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<Label htmlFor="show-proxies" className="flex items-center gap-2 cursor-pointer">
|
||||
<Globe className="h-4 w-4" />
|
||||
<span>Reverse Proxies</span>
|
||||
</Label>
|
||||
<Switch
|
||||
id="show-proxies"
|
||||
checked={filters.showProxies}
|
||||
onCheckedChange={() => toggleFilter("showProxies")}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<Label
|
||||
htmlFor="show-k8s-nodes"
|
||||
className="flex items-center gap-2 cursor-pointer"
|
||||
>
|
||||
<Box className="h-4 w-4" />
|
||||
<span>K8s Nodes</span>
|
||||
</Label>
|
||||
<Switch
|
||||
id="show-k8s-nodes"
|
||||
checked={filters.showK8sNodes}
|
||||
onCheckedChange={() => toggleFilter("showK8sNodes")}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<Label htmlFor="show-connections" className="cursor-pointer">
|
||||
Connection Lines
|
||||
</Label>
|
||||
<Switch
|
||||
id="show-connections"
|
||||
checked={filters.showConnections}
|
||||
onCheckedChange={() => toggleFilter("showConnections")}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
83
apps/web/components/topology/layouts/hierarchical-layout.ts
Normal file
83
apps/web/components/topology/layouts/hierarchical-layout.ts
Normal file
@@ -0,0 +1,83 @@
|
||||
import type { TopologyEdge, TopologyNode } from "@/lib/topology-types";
|
||||
|
||||
const LAYOUT_CONFIG = {
|
||||
TIER_SPACING: 300, // Vertical spacing between proxy and server tiers
|
||||
NODE_SPACING: 250, // Horizontal spacing between nodes
|
||||
START_X: 150, // Left padding
|
||||
START_Y: 100, // Top padding
|
||||
} as const;
|
||||
|
||||
export function applyHierarchicalLayout(
|
||||
nodes: TopologyNode[],
|
||||
edges: TopologyEdge[]
|
||||
): { nodes: TopologyNode[]; edges: TopologyEdge[] } {
|
||||
const proxyNodes = nodes.filter((n) => n.data.type === "proxy");
|
||||
const serverNodes = nodes.filter((n) => n.data.type === "server");
|
||||
|
||||
const layoutedNodes: TopologyNode[] = [];
|
||||
|
||||
const maxNodesInTier = Math.max(proxyNodes.length, serverNodes.length);
|
||||
const tierWidth = maxNodesInTier * LAYOUT_CONFIG.NODE_SPACING;
|
||||
|
||||
const proxyOffsetX = (tierWidth - proxyNodes.length * LAYOUT_CONFIG.NODE_SPACING) / 2;
|
||||
proxyNodes.forEach((node, index) => {
|
||||
const x = LAYOUT_CONFIG.START_X + proxyOffsetX + index * LAYOUT_CONFIG.NODE_SPACING;
|
||||
const y = LAYOUT_CONFIG.START_Y;
|
||||
|
||||
layoutedNodes.push({
|
||||
...node,
|
||||
position: { x, y },
|
||||
});
|
||||
});
|
||||
|
||||
const serverOffsetX = (tierWidth - serverNodes.length * LAYOUT_CONFIG.NODE_SPACING) / 2;
|
||||
serverNodes.forEach((node, index) => {
|
||||
const x = LAYOUT_CONFIG.START_X + serverOffsetX + index * LAYOUT_CONFIG.NODE_SPACING;
|
||||
const y = LAYOUT_CONFIG.START_Y + LAYOUT_CONFIG.TIER_SPACING;
|
||||
|
||||
layoutedNodes.push({
|
||||
...node,
|
||||
position: { x, y },
|
||||
});
|
||||
});
|
||||
|
||||
return {
|
||||
nodes: layoutedNodes,
|
||||
edges,
|
||||
};
|
||||
}
|
||||
|
||||
export function applyGridLayout(
|
||||
nodes: TopologyNode[],
|
||||
edges: TopologyEdge[]
|
||||
): { nodes: TopologyNode[]; edges: TopologyEdge[] } {
|
||||
const columns = Math.ceil(Math.sqrt(nodes.length));
|
||||
|
||||
const layoutedNodes = nodes.map((node, index) => ({
|
||||
...node,
|
||||
position: {
|
||||
x: LAYOUT_CONFIG.START_X + (index % columns) * LAYOUT_CONFIG.NODE_SPACING,
|
||||
y: LAYOUT_CONFIG.START_Y + Math.floor(index / columns) * LAYOUT_CONFIG.TIER_SPACING,
|
||||
},
|
||||
}));
|
||||
|
||||
return {
|
||||
nodes: layoutedNodes,
|
||||
edges,
|
||||
};
|
||||
}
|
||||
|
||||
export function layoutTopologyGraph(
|
||||
nodes: TopologyNode[],
|
||||
edges: TopologyEdge[]
|
||||
): { nodes: TopologyNode[]; edges: TopologyEdge[] } {
|
||||
if (nodes.length === 0) {
|
||||
return { nodes: [], edges: [] };
|
||||
}
|
||||
|
||||
if (nodes.length < 20) {
|
||||
return applyHierarchicalLayout(nodes, edges);
|
||||
}
|
||||
|
||||
return applyGridLayout(nodes, edges);
|
||||
}
|
||||
142
apps/web/components/topology/nodes/k8s-node.tsx
Normal file
142
apps/web/components/topology/nodes/k8s-node.tsx
Normal file
@@ -0,0 +1,142 @@
|
||||
import type { NodeProps } from "@xyflow/react";
|
||||
import { Handle, Position } from "@xyflow/react";
|
||||
import { Box, Cpu, HardDrive, Network, Server as ServerIcon } from "lucide-react";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { cn } from "@/lib/cn";
|
||||
import type { K8sNodeMetadata, TopologyNodeData } from "@/lib/topology-types";
|
||||
|
||||
export function K8sNodeComponent({ data, selected }: NodeProps) {
|
||||
const nodeData = data as TopologyNodeData;
|
||||
const metadata = nodeData.metadata as K8sNodeMetadata;
|
||||
const { node, podCount, serverPods, proxyPods, health, metrics } = metadata;
|
||||
|
||||
const getStatusBadge = () => {
|
||||
switch (health) {
|
||||
case "healthy":
|
||||
return <Badge className="bg-green-500 hover:bg-green-600 text-xs">Healthy</Badge>;
|
||||
case "degraded":
|
||||
return <Badge className="bg-yellow-500 hover:bg-yellow-600 text-xs">Degraded</Badge>;
|
||||
case "unhealthy":
|
||||
return <Badge className="bg-red-500 hover:bg-red-600 text-xs">Unhealthy</Badge>;
|
||||
default:
|
||||
return (
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
Unknown
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"rounded-lg border bg-card p-3 shadow-md hover:shadow-lg transition-all w-[300px]",
|
||||
selected && "ring-2 ring-primary ring-offset-2 shadow-xl"
|
||||
)}
|
||||
>
|
||||
<Handle type="target" position={Position.Top} className="w-3 h-3 !bg-gray-400" />
|
||||
|
||||
<div className="space-y-2.5">
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div className="flex items-center gap-2 flex-1 min-w-0">
|
||||
<div className="rounded-md bg-blue-500/10 p-1.5">
|
||||
<Box className="h-4 w-4 text-blue-600" />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="font-bold text-sm truncate">{node.name || "Unknown"}</p>
|
||||
<p className="text-xs text-muted-foreground">Kubernetes Node</p>
|
||||
</div>
|
||||
</div>
|
||||
{getStatusBadge()}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap gap-1">
|
||||
<Badge variant="outline" className="text-[10px] h-5">
|
||||
{node.status}
|
||||
</Badge>
|
||||
{node.version && (
|
||||
<Badge variant="outline" className="text-[10px] h-5">
|
||||
{node.version}
|
||||
</Badge>
|
||||
)}
|
||||
<Badge variant="outline" className="text-[10px] h-5">
|
||||
{node.roles}
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between text-xs bg-muted/50 rounded px-2 py-1.5">
|
||||
<span className="text-muted-foreground">Total Pods</span>
|
||||
<span className="font-semibold text-blue-600">{podCount}</span>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1 text-[11px]">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-muted-foreground flex items-center gap-1">
|
||||
<ServerIcon className="h-3 w-3" /> Server Pods
|
||||
</span>
|
||||
<span className="font-medium">{serverPods.length}</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-muted-foreground flex items-center gap-1">
|
||||
<Network className="h-3 w-3" /> Proxy Pods
|
||||
</span>
|
||||
<span className="font-medium">{proxyPods.length}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{metrics && (metrics.cpuUsage || metrics.memoryUsage) && (
|
||||
<div className="space-y-1 text-[11px] pt-1 border-t">
|
||||
{metrics.cpuUsage && (
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-muted-foreground flex items-center gap-1">
|
||||
<Cpu className="h-3 w-3" /> CPU
|
||||
</span>
|
||||
<span className="font-semibold text-xs text-blue-600">{metrics.cpuUsage}</span>
|
||||
</div>
|
||||
)}
|
||||
{metrics.memoryUsage && (
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-muted-foreground flex items-center gap-1">
|
||||
<HardDrive className="h-3 w-3" /> Memory
|
||||
</span>
|
||||
<span className="font-semibold text-xs text-blue-600">{metrics.memoryUsage}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-1 text-[11px] pt-1 border-t">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-muted-foreground">Age</span>
|
||||
<span className="font-medium">{node.age}</span>
|
||||
</div>
|
||||
{node.hostname && (
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-muted-foreground">Hostname</span>
|
||||
<span className="font-medium font-mono text-[10px] truncate">{node.hostname}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{(node.internalIP || node.externalIP) && (
|
||||
<div className="space-y-1 text-[11px] pt-1 border-t">
|
||||
{node.internalIP && (
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-muted-foreground">Internal IP</span>
|
||||
<span className="font-mono text-[10px] font-medium">{node.internalIP}</span>
|
||||
</div>
|
||||
)}
|
||||
{node.externalIP && (
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-muted-foreground">External IP</span>
|
||||
<span className="font-mono text-[10px] font-medium">{node.externalIP}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Handle type="source" position={Position.Bottom} className="w-3 h-3 !bg-gray-400" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
9
apps/web/components/topology/nodes/node-types.ts
Normal file
9
apps/web/components/topology/nodes/node-types.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { K8sNodeComponent } from "./k8s-node";
|
||||
import { ProxyNode } from "./proxy-node";
|
||||
import { ServerNode } from "./server-node";
|
||||
|
||||
export const nodeTypes = {
|
||||
server: ServerNode,
|
||||
proxy: ProxyNode,
|
||||
"k8s-node": K8sNodeComponent,
|
||||
};
|
||||
206
apps/web/components/topology/nodes/proxy-node.tsx
Normal file
206
apps/web/components/topology/nodes/proxy-node.tsx
Normal file
@@ -0,0 +1,206 @@
|
||||
import type { NodeProps } from "@xyflow/react";
|
||||
import { Handle, Position } from "@xyflow/react";
|
||||
import { Box, Check, Copy, Cpu, Globe, HardDrive, Network } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { cn } from "@/lib/cn";
|
||||
import type { ProxyMetadata, TopologyNodeData } from "@/lib/topology-types";
|
||||
|
||||
export function ProxyNode({ data, selected }: NodeProps) {
|
||||
const nodeData = data as TopologyNodeData | TopologyNodeData;
|
||||
const metadata = nodeData.metadata as ProxyMetadata | ProxyMetadata;
|
||||
const { proxy, readyPods, podCount, health, connectedServers } = metadata;
|
||||
|
||||
const k8sNodes = "k8sNodes" in metadata ? metadata.k8sNodes : [];
|
||||
const connectionInfo = "connectionInfo" in metadata ? metadata.connectionInfo : null;
|
||||
const metrics = "metrics" in metadata ? metadata.metrics : undefined;
|
||||
|
||||
const [copied, setCopied] = useState(false);
|
||||
|
||||
const handleCopy = async (e: React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
if (connectionInfo?.connectionString) {
|
||||
await navigator.clipboard.writeText(connectionInfo.connectionString);
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
}
|
||||
};
|
||||
|
||||
const getStatusBadge = () => {
|
||||
switch (health) {
|
||||
case "healthy":
|
||||
return <Badge className="bg-green-500 hover:bg-green-600 text-xs">Healthy</Badge>;
|
||||
case "degraded":
|
||||
return <Badge className="bg-yellow-500 hover:bg-yellow-600 text-xs">Degraded</Badge>;
|
||||
case "unhealthy":
|
||||
return <Badge className="bg-red-500 hover:bg-red-600 text-xs">Unhealthy</Badge>;
|
||||
default:
|
||||
return (
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
Unknown
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"rounded-lg border bg-card p-3 shadow-md hover:shadow-lg transition-all w-[300px]",
|
||||
selected && "ring-2 ring-primary ring-offset-2 shadow-xl"
|
||||
)}
|
||||
>
|
||||
<Handle type="target" position={Position.Top} className="w-3 h-3 !bg-gray-400" />
|
||||
|
||||
<div className="space-y-2.5">
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div className="flex items-center gap-2 flex-1 min-w-0">
|
||||
<div className="rounded-md bg-blue-500/10 p-1.5">
|
||||
<Globe className="h-4 w-4 text-blue-500" />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="font-bold text-sm truncate">{proxy.id}</p>
|
||||
{proxy.description && (
|
||||
<p className="text-xs text-muted-foreground truncate">{proxy.description}</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{getStatusBadge()}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap gap-1">
|
||||
<Badge variant="outline" className="text-[10px] h-5">
|
||||
{proxy.type}
|
||||
</Badge>
|
||||
{connectionInfo && (
|
||||
<Badge variant="outline" className="text-[10px] h-5">
|
||||
{connectionInfo.type}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between text-xs bg-muted/50 rounded px-2 py-1.5">
|
||||
<span className="text-muted-foreground">Pods</span>
|
||||
<span
|
||||
className={cn(
|
||||
"font-semibold",
|
||||
readyPods === podCount ? "text-green-600" : "text-yellow-600"
|
||||
)}
|
||||
>
|
||||
{readyPods}/{podCount}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{proxy.node_port && (
|
||||
<div className="space-y-1 text-[11px]">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-muted-foreground flex items-center gap-1">
|
||||
<Network className="h-3 w-3" /> NodePort
|
||||
</span>
|
||||
<span className="font-medium">{proxy.node_port}</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{connectionInfo?.connectionString && (
|
||||
<div className="space-y-1 text-[11px] pt-1 border-t">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-muted-foreground">Address</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<code className="text-[10px] bg-muted px-1.5 py-0.5 rounded font-mono flex-1 truncate">
|
||||
{connectionInfo.connectionString}
|
||||
</code>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-5 w-5 shrink-0"
|
||||
onClick={handleCopy}
|
||||
title={copied ? "Copied!" : "Copy address"}
|
||||
>
|
||||
{copied ? (
|
||||
<Check className="h-3 w-3 text-green-500" />
|
||||
) : (
|
||||
<Copy className="h-3 w-3" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
{connectionInfo.note && (
|
||||
<p className="text-[10px] text-muted-foreground italic">{connectionInfo.note}</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-1 text-[11px] pt-1 border-t">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-muted-foreground flex items-center gap-1">
|
||||
<HardDrive className="h-3 w-3" /> Memory
|
||||
</span>
|
||||
<span className="font-medium text-xs">
|
||||
{metrics?.memoryUsage && (
|
||||
<span className="text-blue-600">{metrics.memoryUsage} / </span>
|
||||
)}
|
||||
<span className="text-muted-foreground">{proxy.memory}MB</span>
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-muted-foreground flex items-center gap-1">
|
||||
<Cpu className="h-3 w-3" /> CPU
|
||||
</span>
|
||||
<span className="font-medium text-xs">
|
||||
{metrics?.cpuUsage && <span className="text-blue-600">{metrics.cpuUsage} / </span>}
|
||||
<span className="text-muted-foreground">
|
||||
{proxy.cpu_request || "N/A"}/{proxy.cpu_limit || "N/A"}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{"pods" in metadata && metadata.pods && metadata.pods.length > 0 && (
|
||||
<div className="space-y-1 text-[11px] pt-1 border-t">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-muted-foreground">Restarts</span>
|
||||
<span
|
||||
className={cn(
|
||||
"font-medium",
|
||||
metadata.pods.reduce((sum, p) => sum + (p.restarts || 0), 0) > 0
|
||||
? "text-yellow-600"
|
||||
: "text-green-600"
|
||||
)}
|
||||
>
|
||||
{metadata.pods.reduce((sum, p) => sum + (p.restarts || 0), 0)}
|
||||
</span>
|
||||
</div>
|
||||
{metadata.pods[0]?.age && (
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-muted-foreground">Age</span>
|
||||
<span className="font-medium">{metadata.pods[0].age}</span>
|
||||
</div>
|
||||
)}
|
||||
{metadata.pods[0]?.ip && (
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-muted-foreground">Pod IP</span>
|
||||
<span className="font-medium font-mono text-[10px]">{metadata.pods[0].ip}</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-muted-foreground">Routing To</span>
|
||||
<span className="font-semibold text-blue-600">{connectedServers.length} servers</span>
|
||||
</div>
|
||||
{k8sNodes.length > 0 && (
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-muted-foreground flex items-center gap-1">
|
||||
<Box className="h-3 w-3" /> K8s Node
|
||||
</span>
|
||||
<span className="font-medium">{k8sNodes[0]}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Handle type="source" position={Position.Bottom} className="w-3 h-3 !bg-gray-400" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
210
apps/web/components/topology/nodes/server-node.tsx
Normal file
210
apps/web/components/topology/nodes/server-node.tsx
Normal file
@@ -0,0 +1,210 @@
|
||||
import type { NodeProps } from "@xyflow/react";
|
||||
import { Handle, Position } from "@xyflow/react";
|
||||
import { Box, Check, Copy, Cpu, HardDrive, Server } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { cn } from "@/lib/cn";
|
||||
import type { ServerMetadata, TopologyNodeData } from "@/lib/topology-types";
|
||||
|
||||
export function ServerNode({ data, selected }: NodeProps) {
|
||||
const nodeData = data as TopologyNodeData | TopologyNodeData;
|
||||
const metadata = nodeData.metadata as ServerMetadata | ServerMetadata;
|
||||
const { server, readyPods, podCount, health } = metadata;
|
||||
|
||||
const k8sNodes = "k8sNodes" in metadata ? metadata.k8sNodes : [];
|
||||
const connectedProxies = "connectedProxies" in metadata ? metadata.connectedProxies : [];
|
||||
const connectionInfo = "connectionInfo" in metadata ? metadata.connectionInfo : null;
|
||||
const metrics = "metrics" in metadata ? metadata.metrics : undefined;
|
||||
|
||||
const [copied, setCopied] = useState(false);
|
||||
|
||||
const handleCopy = async (e: React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
if (connectionInfo?.connectionString) {
|
||||
await navigator.clipboard.writeText(connectionInfo.connectionString);
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
}
|
||||
};
|
||||
|
||||
const getStatusBadge = () => {
|
||||
switch (health) {
|
||||
case "healthy":
|
||||
return <Badge className="bg-green-500 hover:bg-green-600 text-xs">Healthy</Badge>;
|
||||
case "degraded":
|
||||
return <Badge className="bg-yellow-500 hover:bg-yellow-600 text-xs">Degraded</Badge>;
|
||||
case "unhealthy":
|
||||
return <Badge className="bg-red-500 hover:bg-red-600 text-xs">Unhealthy</Badge>;
|
||||
default:
|
||||
return (
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
Unknown
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"rounded-lg border bg-card p-3 shadow-md hover:shadow-lg transition-all w-[300px]",
|
||||
selected && "ring-2 ring-primary ring-offset-2 shadow-xl"
|
||||
)}
|
||||
>
|
||||
<Handle type="target" position={Position.Top} className="w-3 h-3 !bg-gray-400" />
|
||||
|
||||
<div className="space-y-2.5">
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div className="flex items-center gap-2 flex-1 min-w-0">
|
||||
<div className="rounded-md bg-primary/10 p-1.5">
|
||||
<Server className="h-4 w-4 text-primary" />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="font-bold text-sm truncate">{server.id}</p>
|
||||
{server.description && (
|
||||
<p className="text-xs text-muted-foreground truncate">{server.description}</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{getStatusBadge()}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap gap-1">
|
||||
<Badge variant="outline" className="text-[10px] h-5">
|
||||
{server.jar_type}
|
||||
</Badge>
|
||||
<Badge variant="outline" className="text-[10px] h-5">
|
||||
MC {server.minecraft_version}
|
||||
</Badge>
|
||||
<Badge variant="outline" className="text-[10px] h-5">
|
||||
{server.type}
|
||||
</Badge>
|
||||
{connectionInfo && (
|
||||
<Badge variant="outline" className="text-[10px] h-5">
|
||||
{connectionInfo.type}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between text-xs bg-muted/50 rounded px-2 py-1.5">
|
||||
<span className="text-muted-foreground">Pods</span>
|
||||
<span
|
||||
className={cn(
|
||||
"font-semibold",
|
||||
readyPods === podCount ? "text-green-600" : "text-yellow-600"
|
||||
)}
|
||||
>
|
||||
{readyPods}/{podCount}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1 text-[11px]">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-muted-foreground flex items-center gap-1">
|
||||
<HardDrive className="h-3 w-3" /> Memory
|
||||
</span>
|
||||
<span className="font-medium text-xs">
|
||||
{metrics?.memoryUsage && (
|
||||
<span className="text-blue-600">{metrics.memoryUsage} / </span>
|
||||
)}
|
||||
<span className="text-muted-foreground">
|
||||
{server.memory_request}/{server.memory}MB
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-muted-foreground flex items-center gap-1">
|
||||
<Cpu className="h-3 w-3" /> CPU
|
||||
</span>
|
||||
<span className="font-medium text-xs">
|
||||
{metrics?.cpuUsage && <span className="text-blue-600">{metrics.cpuUsage} / </span>}
|
||||
<span className="text-muted-foreground">
|
||||
{server.cpu_request || "N/A"}/{server.cpu_limit || "N/A"}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{connectionInfo?.connectionString && (
|
||||
<div className="space-y-1 text-[11px] pt-1 border-t">
|
||||
<div className="flex items-center gap-1">
|
||||
<code className="text-[10px] bg-muted px-1.5 py-0.5 rounded font-mono flex-1 truncate">
|
||||
{connectionInfo.connectionString}
|
||||
</code>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-5 w-5 shrink-0"
|
||||
onClick={handleCopy}
|
||||
title={copied ? "Copied!" : "Copy address"}
|
||||
>
|
||||
{copied ? (
|
||||
<Check className="h-3 w-3 text-green-500" />
|
||||
) : (
|
||||
<Copy className="h-3 w-3" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
{connectionInfo.note && (
|
||||
<p className="text-[10px] text-muted-foreground italic">{connectionInfo.note}</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{"pods" in metadata && metadata.pods && metadata.pods.length > 0 && (
|
||||
<div className="space-y-1 text-[11px] pt-1 border-t">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-muted-foreground">Restarts</span>
|
||||
<span
|
||||
className={cn(
|
||||
"font-medium",
|
||||
metadata.pods.reduce((sum, p) => sum + (p.restarts || 0), 0) > 0
|
||||
? "text-yellow-600"
|
||||
: "text-green-600"
|
||||
)}
|
||||
>
|
||||
{metadata.pods.reduce((sum, p) => sum + (p.restarts || 0), 0)}
|
||||
</span>
|
||||
</div>
|
||||
{metadata.pods[0]?.age && (
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-muted-foreground">Age</span>
|
||||
<span className="font-medium">{metadata.pods[0].age}</span>
|
||||
</div>
|
||||
)}
|
||||
{metadata.pods[0]?.ip && (
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-muted-foreground">Pod IP</span>
|
||||
<span className="font-medium font-mono text-[10px]">{metadata.pods[0].ip}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{(k8sNodes.length > 0 || connectedProxies.length > 0) && (
|
||||
<div className="space-y-1 text-[11px] pt-1 border-t">
|
||||
{connectedProxies.length > 0 && (
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-muted-foreground">Exposed By</span>
|
||||
<span className="font-semibold text-blue-600">
|
||||
{connectedProxies.length} proxies
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
{k8sNodes.length > 0 && (
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-muted-foreground flex items-center gap-1">
|
||||
<Box className="h-3 w-3" /> K8s Node
|
||||
</span>
|
||||
<span className="font-medium">{k8sNodes[0]}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Handle type="source" position={Position.Bottom} className="w-3 h-3 !bg-gray-400" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
128
apps/web/components/topology/topology-canvas.tsx
Normal file
128
apps/web/components/topology/topology-canvas.tsx
Normal file
@@ -0,0 +1,128 @@
|
||||
"use client";
|
||||
|
||||
import { Background, BackgroundVariant, Controls, MiniMap, Panel, ReactFlow } from "@xyflow/react";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import "@xyflow/react/dist/style.css";
|
||||
import { useGraphLayout } from "@/hooks/use-graph-layout";
|
||||
import type { TopologyFilters, TopologyGraph, TopologyNodeData } from "@/lib/topology-types";
|
||||
import { filterEdges, filterNodes } from "@/lib/topology-utils";
|
||||
import { NodeDetailsPanel } from "./controls/node-details-panel";
|
||||
import { TopologyToolbar } from "./controls/topology-toolbar";
|
||||
import { nodeTypes } from "./nodes/node-types";
|
||||
|
||||
interface TopologyCanvasProps {
|
||||
graph: TopologyGraph;
|
||||
}
|
||||
|
||||
export function TopologyCanvas({ graph }: TopologyCanvasProps) {
|
||||
const [selectedNode, setSelectedNode] = useState<TopologyNodeData | null>(null);
|
||||
const [filters, setFilters] = useState<TopologyFilters>({
|
||||
showServers: true,
|
||||
showProxies: true,
|
||||
showK8sNodes: true,
|
||||
showConnections: true,
|
||||
searchQuery: "",
|
||||
});
|
||||
|
||||
const filteredNodes = useMemo(() => {
|
||||
return filterNodes(graph.nodes, filters);
|
||||
}, [graph.nodes, filters]);
|
||||
|
||||
const filteredEdges = useMemo(() => {
|
||||
if (!filters.showConnections) return [];
|
||||
const visibleNodeIds = new Set(filteredNodes.map((node) => node.id));
|
||||
return filterEdges(graph.edges, visibleNodeIds);
|
||||
}, [graph.edges, filteredNodes, filters.showConnections]);
|
||||
|
||||
const { nodes, edges } = useGraphLayout({
|
||||
nodes: filteredNodes,
|
||||
edges: filteredEdges,
|
||||
});
|
||||
|
||||
const onNodeClick = useCallback((_event: React.MouseEvent, node: any) => {
|
||||
setSelectedNode(node.data as TopologyNodeData);
|
||||
}, []);
|
||||
|
||||
const onPaneClick = useCallback(() => {
|
||||
setSelectedNode(null);
|
||||
}, []);
|
||||
|
||||
const handleCloseDetails = useCallback(() => {
|
||||
setSelectedNode(null);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="h-[calc(100vh-250px)] w-full rounded-lg border bg-background shadow-xl">
|
||||
<ReactFlow
|
||||
nodes={nodes}
|
||||
edges={edges}
|
||||
nodeTypes={nodeTypes}
|
||||
onNodeClick={onNodeClick}
|
||||
onPaneClick={onPaneClick}
|
||||
fitView
|
||||
fitViewOptions={{
|
||||
padding: 0.2,
|
||||
includeHiddenNodes: false,
|
||||
minZoom: 0.1,
|
||||
maxZoom: 1.5,
|
||||
}}
|
||||
minZoom={0.1}
|
||||
maxZoom={1.5}
|
||||
defaultEdgeOptions={{
|
||||
animated: false,
|
||||
type: "smoothstep",
|
||||
style: {
|
||||
stroke: "#9ca3af",
|
||||
strokeWidth: 2,
|
||||
strokeDasharray: "5 5",
|
||||
},
|
||||
markerEnd: {
|
||||
type: "arrowclosed",
|
||||
color: "#9ca3af",
|
||||
width: 20,
|
||||
height: 20,
|
||||
},
|
||||
}}
|
||||
proOptions={{ hideAttribution: true }}
|
||||
>
|
||||
<Background variant={BackgroundVariant.Dots} color="#cbd5e1" gap={24} size={1} />
|
||||
<Controls
|
||||
showZoom
|
||||
showFitView
|
||||
showInteractive
|
||||
className="bg-white/80 backdrop-blur-sm border shadow-lg"
|
||||
/>
|
||||
<MiniMap
|
||||
nodeColor={(node: any) => {
|
||||
const data = node.data as TopologyNodeData;
|
||||
const colors = {
|
||||
healthy: "#22c55e",
|
||||
degraded: "#eab308",
|
||||
unhealthy: "#ef4444",
|
||||
unknown: "#94a3b8",
|
||||
};
|
||||
return colors[data.status] || "#94a3b8";
|
||||
}}
|
||||
maskColor="rgba(0, 0, 0, 0.05)"
|
||||
className="bg-white/80 backdrop-blur-sm border shadow-lg"
|
||||
/>
|
||||
|
||||
<Panel position="top-left">
|
||||
<div className="m-2">
|
||||
<TopologyToolbar
|
||||
filters={filters}
|
||||
onFiltersChange={setFilters}
|
||||
metadata={graph.metadata}
|
||||
/>
|
||||
</div>
|
||||
</Panel>
|
||||
</ReactFlow>
|
||||
|
||||
<NodeDetailsPanel
|
||||
node={selectedNode}
|
||||
open={selectedNode !== null}
|
||||
onClose={handleCloseDetails}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,24 +1,20 @@
|
||||
"use client"
|
||||
"use client";
|
||||
|
||||
import * as React from "react"
|
||||
import * as AccordionPrimitive from "@radix-ui/react-accordion"
|
||||
import { ChevronDown } from "lucide-react"
|
||||
import * as AccordionPrimitive from "@radix-ui/react-accordion";
|
||||
import { ChevronDown } from "lucide-react";
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { cn } from "@/lib/cn";
|
||||
|
||||
const Accordion = AccordionPrimitive.Root
|
||||
const Accordion = AccordionPrimitive.Root;
|
||||
|
||||
const AccordionItem = React.forwardRef<
|
||||
React.ElementRef<typeof AccordionPrimitive.Item>,
|
||||
React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Item>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<AccordionPrimitive.Item
|
||||
ref={ref}
|
||||
className={cn("border-b", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
AccordionItem.displayName = "AccordionItem"
|
||||
<AccordionPrimitive.Item ref={ref} className={cn("border-b", className)} {...props} />
|
||||
));
|
||||
AccordionItem.displayName = "AccordionItem";
|
||||
|
||||
const AccordionTrigger = React.forwardRef<
|
||||
React.ElementRef<typeof AccordionPrimitive.Trigger>,
|
||||
@@ -37,8 +33,8 @@ const AccordionTrigger = React.forwardRef<
|
||||
<ChevronDown className="h-4 w-4 shrink-0 transition-transform duration-200" />
|
||||
</AccordionPrimitive.Trigger>
|
||||
</AccordionPrimitive.Header>
|
||||
))
|
||||
AccordionTrigger.displayName = AccordionPrimitive.Trigger.displayName
|
||||
));
|
||||
AccordionTrigger.displayName = AccordionPrimitive.Trigger.displayName;
|
||||
|
||||
const AccordionContent = React.forwardRef<
|
||||
React.ElementRef<typeof AccordionPrimitive.Content>,
|
||||
@@ -51,8 +47,8 @@ const AccordionContent = React.forwardRef<
|
||||
>
|
||||
<div className={cn("pb-4 pt-0", className)}>{children}</div>
|
||||
</AccordionPrimitive.Content>
|
||||
))
|
||||
));
|
||||
|
||||
AccordionContent.displayName = AccordionPrimitive.Content.displayName
|
||||
AccordionContent.displayName = AccordionPrimitive.Content.displayName;
|
||||
|
||||
export { Accordion, AccordionItem, AccordionTrigger, AccordionContent }
|
||||
export { Accordion, AccordionItem, AccordionTrigger, AccordionContent };
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"use client";
|
||||
|
||||
import type * as React from "react";
|
||||
import * as AvatarPrimitive from "@radix-ui/react-avatar";
|
||||
import type * as React from "react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
import { cn } from "@/lib/cn";
|
||||
|
||||
function Avatar({ className, ...props }: React.ComponentProps<typeof AvatarPrimitive.Root>) {
|
||||
return (
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import type * as React from "react";
|
||||
import { Slot } from "@radix-ui/react-slot";
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
import type * as React from "react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
import { cn } from "@/lib/cn";
|
||||
|
||||
const badgeVariants = cva(
|
||||
"inline-flex items-center justify-center rounded-full border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import type * as React from "react";
|
||||
import { Slot } from "@radix-ui/react-slot";
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
import type * as React from "react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
import { cn } from "@/lib/cn";
|
||||
|
||||
const buttonVariants = cva(
|
||||
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type * as React from "react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
import { cn } from "@/lib/cn";
|
||||
|
||||
function Card({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
"use client"
|
||||
"use client";
|
||||
|
||||
import * as React from "react"
|
||||
import * as CheckboxPrimitive from "@radix-ui/react-checkbox"
|
||||
import { Check } from "lucide-react"
|
||||
import * as CheckboxPrimitive from "@radix-ui/react-checkbox";
|
||||
import { Check } from "lucide-react";
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { cn } from "@/lib/cn";
|
||||
|
||||
const Checkbox = React.forwardRef<
|
||||
React.ElementRef<typeof CheckboxPrimitive.Root>,
|
||||
@@ -18,13 +18,11 @@ const Checkbox = React.forwardRef<
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<CheckboxPrimitive.Indicator
|
||||
className={cn("flex items-center justify-center text-current")}
|
||||
>
|
||||
<CheckboxPrimitive.Indicator className={cn("flex items-center justify-center text-current")}>
|
||||
<Check className="h-4 w-4" />
|
||||
</CheckboxPrimitive.Indicator>
|
||||
</CheckboxPrimitive.Root>
|
||||
))
|
||||
Checkbox.displayName = CheckboxPrimitive.Root.displayName
|
||||
));
|
||||
Checkbox.displayName = CheckboxPrimitive.Root.displayName;
|
||||
|
||||
export { Checkbox }
|
||||
export { Checkbox };
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
"use client";
|
||||
|
||||
import type * as React from "react";
|
||||
import * as DialogPrimitive from "@radix-ui/react-dialog";
|
||||
import { XIcon } from "lucide-react";
|
||||
import type * as React from "react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
import { cn } from "@/lib/cn";
|
||||
|
||||
function Dialog({ ...props }: React.ComponentProps<typeof DialogPrimitive.Root>) {
|
||||
return <DialogPrimitive.Root data-slot="dialog" {...props} />;
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
"use client";
|
||||
|
||||
import type * as React from "react";
|
||||
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu";
|
||||
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react";
|
||||
import type * as React from "react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
import { cn } from "@/lib/cn";
|
||||
|
||||
function DropdownMenu({ ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
|
||||
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />;
|
||||
|
||||
@@ -1,20 +1,19 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import type * as LabelPrimitive from "@radix-ui/react-label";
|
||||
import { Slot } from "@radix-ui/react-slot";
|
||||
import * as React from "react";
|
||||
import {
|
||||
Controller,
|
||||
FormProvider,
|
||||
useFormContext,
|
||||
useFormState,
|
||||
type ControllerProps,
|
||||
type FieldPath,
|
||||
type FieldValues,
|
||||
FormProvider,
|
||||
useFormContext,
|
||||
useFormState,
|
||||
} from "react-hook-form";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { cn } from "@/lib/cn";
|
||||
|
||||
const Form = FormProvider;
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type * as React from "react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
import { cn } from "@/lib/cn";
|
||||
|
||||
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
|
||||
return (
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"use client";
|
||||
|
||||
import type * as React from "react";
|
||||
import * as LabelPrimitive from "@radix-ui/react-label";
|
||||
import type * as React from "react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
import { cn } from "@/lib/cn";
|
||||
|
||||
function Label({ className, ...props }: React.ComponentProps<typeof LabelPrimitive.Root>) {
|
||||
return (
|
||||
|
||||
31
apps/web/components/ui/popover.tsx
Normal file
31
apps/web/components/ui/popover.tsx
Normal file
@@ -0,0 +1,31 @@
|
||||
"use client";
|
||||
|
||||
import * as PopoverPrimitive from "@radix-ui/react-popover";
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from "@/lib/cn";
|
||||
|
||||
const Popover = PopoverPrimitive.Root;
|
||||
|
||||
const PopoverTrigger = PopoverPrimitive.Trigger;
|
||||
|
||||
const PopoverContent = React.forwardRef<
|
||||
React.ElementRef<typeof PopoverPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>
|
||||
>(({ className, align = "center", sideOffset = 4, ...props }, ref) => (
|
||||
<PopoverPrimitive.Portal>
|
||||
<PopoverPrimitive.Content
|
||||
ref={ref}
|
||||
align={align}
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</PopoverPrimitive.Portal>
|
||||
));
|
||||
PopoverContent.displayName = PopoverPrimitive.Content.displayName;
|
||||
|
||||
export { Popover, PopoverTrigger, PopoverContent };
|
||||
@@ -1,10 +1,10 @@
|
||||
"use client";
|
||||
|
||||
import type * as React from "react";
|
||||
import * as SelectPrimitive from "@radix-ui/react-select";
|
||||
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react";
|
||||
import type * as React from "react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
import { cn } from "@/lib/cn";
|
||||
|
||||
function Select({ ...props }: React.ComponentProps<typeof SelectPrimitive.Root>) {
|
||||
return <SelectPrimitive.Root data-slot="select" {...props} />;
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"use client";
|
||||
|
||||
import type * as React from "react";
|
||||
import * as SeparatorPrimitive from "@radix-ui/react-separator";
|
||||
import type * as React from "react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
import { cn } from "@/lib/cn";
|
||||
|
||||
function Separator({
|
||||
className,
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
"use client";
|
||||
|
||||
import type * as React from "react";
|
||||
import * as SheetPrimitive from "@radix-ui/react-dialog";
|
||||
import { XIcon } from "lucide-react";
|
||||
import type * as React from "react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
import { cn } from "@/lib/cn";
|
||||
|
||||
function Sheet({ ...props }: React.ComponentProps<typeof SheetPrimitive.Root>) {
|
||||
return <SheetPrimitive.Root data-slot="sheet" {...props} />;
|
||||
|
||||
@@ -16,7 +16,7 @@ import {
|
||||
} from "@/components/ui/sheet";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { cn } from "@/lib/cn";
|
||||
|
||||
const SIDEBAR_COOKIE_NAME = "sidebar_state";
|
||||
const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7;
|
||||
@@ -82,7 +82,7 @@ function SidebarProvider({
|
||||
} else {
|
||||
setOpen((open) => !open);
|
||||
}
|
||||
}, [setOpen, setOpenMobile]);
|
||||
}, [setOpen]);
|
||||
|
||||
React.useEffect(() => {
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
@@ -107,7 +107,7 @@ function SidebarProvider({
|
||||
setOpenMobile,
|
||||
toggleSidebar,
|
||||
}),
|
||||
[state, open, setOpen, openMobile, setOpenMobile, toggleSidebar]
|
||||
[state, open, setOpen, openMobile, toggleSidebar]
|
||||
);
|
||||
|
||||
return (
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { cn } from "@/lib/utils";
|
||||
import { cn } from "@/lib/cn";
|
||||
|
||||
function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
|
||||
29
apps/web/components/ui/switch.tsx
Normal file
29
apps/web/components/ui/switch.tsx
Normal file
@@ -0,0 +1,29 @@
|
||||
"use client";
|
||||
|
||||
import * as SwitchPrimitives from "@radix-ui/react-switch";
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from "@/lib/cn";
|
||||
|
||||
const Switch = React.forwardRef<
|
||||
React.ElementRef<typeof SwitchPrimitives.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof SwitchPrimitives.Root>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SwitchPrimitives.Root
|
||||
className={cn(
|
||||
"peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
ref={ref}
|
||||
>
|
||||
<SwitchPrimitives.Thumb
|
||||
className={cn(
|
||||
"pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0"
|
||||
)}
|
||||
/>
|
||||
</SwitchPrimitives.Root>
|
||||
));
|
||||
Switch.displayName = SwitchPrimitives.Root.displayName;
|
||||
|
||||
export { Switch };
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import type * as React from "react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
import { cn } from "@/lib/cn";
|
||||
|
||||
function Table({ className, ...props }: React.ComponentProps<"table">) {
|
||||
return (
|
||||
|
||||
@@ -1,27 +1,21 @@
|
||||
"use client"
|
||||
"use client";
|
||||
|
||||
import * as React from "react"
|
||||
import * as TabsPrimitive from "@radix-ui/react-tabs"
|
||||
import * as TabsPrimitive from "@radix-ui/react-tabs";
|
||||
import type * as React from "react";
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { cn } from "@/lib/cn";
|
||||
|
||||
function Tabs({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TabsPrimitive.Root>) {
|
||||
function Tabs({ className, ...props }: React.ComponentProps<typeof TabsPrimitive.Root>) {
|
||||
return (
|
||||
<TabsPrimitive.Root
|
||||
data-slot="tabs"
|
||||
className={cn("flex flex-col gap-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function TabsList({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TabsPrimitive.List>) {
|
||||
function TabsList({ className, ...props }: React.ComponentProps<typeof TabsPrimitive.List>) {
|
||||
return (
|
||||
<TabsPrimitive.List
|
||||
data-slot="tabs-list"
|
||||
@@ -31,13 +25,10 @@ function TabsList({
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function TabsTrigger({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TabsPrimitive.Trigger>) {
|
||||
function TabsTrigger({ className, ...props }: React.ComponentProps<typeof TabsPrimitive.Trigger>) {
|
||||
return (
|
||||
<TabsPrimitive.Trigger
|
||||
data-slot="tabs-trigger"
|
||||
@@ -47,20 +38,17 @@ function TabsTrigger({
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function TabsContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TabsPrimitive.Content>) {
|
||||
function TabsContent({ className, ...props }: React.ComponentProps<typeof TabsPrimitive.Content>) {
|
||||
return (
|
||||
<TabsPrimitive.Content
|
||||
data-slot="tabs-content"
|
||||
className={cn("flex-1 outline-none", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export { Tabs, TabsList, TabsTrigger, TabsContent }
|
||||
export { Tabs, TabsList, TabsTrigger, TabsContent };
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
import { cn } from "@/lib/cn";
|
||||
|
||||
export interface TextareaProps
|
||||
extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {}
|
||||
export interface TextareaProps extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {}
|
||||
|
||||
const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(
|
||||
({ className, ...props }, ref) => {
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"use client";
|
||||
|
||||
import type * as React from "react";
|
||||
import * as TooltipPrimitive from "@radix-ui/react-tooltip";
|
||||
import type * as React from "react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
import { cn } from "@/lib/cn";
|
||||
|
||||
function TooltipProvider({
|
||||
delayDuration = 0,
|
||||
|
||||
163
apps/web/hooks/use-graph-layout.ts
Normal file
163
apps/web/hooks/use-graph-layout.ts
Normal file
@@ -0,0 +1,163 @@
|
||||
"use client";
|
||||
|
||||
import { Position } from "@xyflow/react";
|
||||
import { useMemo } from "react";
|
||||
import type {
|
||||
ProxyMetadata,
|
||||
ServerMetadata,
|
||||
TopologyEdge,
|
||||
TopologyNode,
|
||||
} from "@/lib/topology-types";
|
||||
|
||||
interface LayoutInput {
|
||||
nodes: TopologyNode[];
|
||||
edges: TopologyEdge[];
|
||||
}
|
||||
|
||||
export function useGraphLayout({ nodes, edges }: LayoutInput) {
|
||||
const layoutedNodes = useMemo(() => {
|
||||
const k8sNodes = nodes.filter((n) => n.data.type === "k8s-node");
|
||||
const serverNodes = nodes.filter((n) => n.data.type === "server");
|
||||
const proxyNodes = nodes.filter((n) => n.data.type === "proxy");
|
||||
|
||||
const nodeSpacing = {
|
||||
x: 350,
|
||||
y: 350,
|
||||
};
|
||||
|
||||
const nodeWidth = 320;
|
||||
const layoutedNodesList: TopologyNode[] = [];
|
||||
|
||||
const k8sNodeGroups = new Map<string, TopologyNode[]>();
|
||||
const orphanedNodes: TopologyNode[] = [];
|
||||
|
||||
const appNodes = [...serverNodes, ...proxyNodes];
|
||||
|
||||
appNodes.forEach((node) => {
|
||||
const metadata = node.data.metadata as ServerMetadata | ProxyMetadata;
|
||||
const k8sNodeNames = metadata.k8sNodes || [];
|
||||
|
||||
if (k8sNodeNames.length === 0) {
|
||||
orphanedNodes.push(node);
|
||||
} else {
|
||||
const k8sNodeName = k8sNodeNames[0];
|
||||
const k8sNodeId = `k8s-node-${k8sNodeName}`;
|
||||
if (!k8sNodeGroups.has(k8sNodeId)) {
|
||||
k8sNodeGroups.set(k8sNodeId, []);
|
||||
}
|
||||
k8sNodeGroups.get(k8sNodeId)?.push(node);
|
||||
}
|
||||
});
|
||||
|
||||
const k8sWithApps = k8sNodes.filter((k8s) => {
|
||||
const group = k8sNodeGroups.get(k8s.id) || [];
|
||||
return group.length > 0;
|
||||
});
|
||||
|
||||
const k8sWithoutApps = k8sNodes.filter((k8s) => {
|
||||
const group = k8sNodeGroups.get(k8s.id) || [];
|
||||
return group.length === 0;
|
||||
});
|
||||
|
||||
const k8sNodeWidths = new Map<string, number>();
|
||||
k8sWithApps.forEach((k8sNode) => {
|
||||
const group = k8sNodeGroups.get(k8sNode.id) || [];
|
||||
const width = Math.max(nodeWidth, group.length * nodeWidth);
|
||||
k8sNodeWidths.set(k8sNode.id, width);
|
||||
});
|
||||
|
||||
let currentX = 0;
|
||||
const k8sNodePositions = new Map<string, { x: number; width: number }>();
|
||||
|
||||
k8sWithApps.forEach((k8sNode) => {
|
||||
const width = k8sNodeWidths.get(k8sNode.id)!;
|
||||
const centerX = currentX + width / 2;
|
||||
|
||||
k8sNodePositions.set(k8sNode.id, { x: centerX, width });
|
||||
|
||||
layoutedNodesList.push({
|
||||
...k8sNode,
|
||||
position: {
|
||||
x: centerX,
|
||||
y: 0,
|
||||
},
|
||||
targetPosition: Position.Top,
|
||||
sourcePosition: Position.Bottom,
|
||||
});
|
||||
|
||||
currentX += width + nodeSpacing.x;
|
||||
});
|
||||
|
||||
k8sWithoutApps.forEach((k8sNode) => {
|
||||
const centerX = currentX + nodeWidth / 2;
|
||||
|
||||
k8sNodePositions.set(k8sNode.id, { x: centerX, width: nodeWidth });
|
||||
|
||||
layoutedNodesList.push({
|
||||
...k8sNode,
|
||||
position: {
|
||||
x: centerX,
|
||||
y: 0,
|
||||
},
|
||||
targetPosition: Position.Top,
|
||||
sourcePosition: Position.Bottom,
|
||||
});
|
||||
|
||||
currentX += nodeWidth + nodeSpacing.x;
|
||||
});
|
||||
|
||||
k8sNodeGroups.forEach((group, k8sNodeId) => {
|
||||
const k8sPos = k8sNodePositions.get(k8sNodeId);
|
||||
if (!k8sPos) return;
|
||||
|
||||
const groupWidth = group.length * nodeWidth;
|
||||
const startX = k8sPos.x - groupWidth / 2 + nodeWidth / 2;
|
||||
|
||||
group.forEach((node, index) => {
|
||||
const xPos = startX + index * nodeWidth;
|
||||
|
||||
layoutedNodesList.push({
|
||||
...node,
|
||||
position: {
|
||||
x: xPos,
|
||||
y: nodeSpacing.y,
|
||||
},
|
||||
targetPosition: Position.Top,
|
||||
sourcePosition: Position.Bottom,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
orphanedNodes.forEach((node, index) => {
|
||||
const xPos = currentX + index * nodeWidth;
|
||||
|
||||
layoutedNodesList.push({
|
||||
...node,
|
||||
position: {
|
||||
x: xPos,
|
||||
y: nodeSpacing.y,
|
||||
},
|
||||
targetPosition: Position.Top,
|
||||
sourcePosition: Position.Bottom,
|
||||
});
|
||||
});
|
||||
|
||||
if (layoutedNodesList.length > 0) {
|
||||
const minX = Math.min(...layoutedNodesList.map((n) => n.position.x));
|
||||
const maxX = Math.max(...layoutedNodesList.map((n) => n.position.x));
|
||||
const totalWidth = maxX - minX;
|
||||
const offsetX = -totalWidth / 2;
|
||||
|
||||
layoutedNodesList.forEach((node) => {
|
||||
node.position.x += offsetX;
|
||||
});
|
||||
}
|
||||
|
||||
return layoutedNodesList;
|
||||
}, [nodes]);
|
||||
|
||||
return {
|
||||
nodes: layoutedNodes,
|
||||
edges,
|
||||
};
|
||||
}
|
||||
@@ -10,7 +10,7 @@ import type {
|
||||
} from "@minikura/api";
|
||||
import { LABEL_PREFIX } from "@minikura/api";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { api } from "@/lib/api";
|
||||
import { api } from "@/lib/api-client";
|
||||
|
||||
export function useK8sResources() {
|
||||
const [statefulSets, setStatefulSets] = useState<StatefulSetInfo[]>([]);
|
||||
@@ -19,15 +19,15 @@ export function useK8sResources() {
|
||||
const [configMaps, setConfigMaps] = useState<K8sConfigMapSummary[]>([]);
|
||||
const [minecraftServers, setMinecraftServers] = useState<CustomResourceSummary[]>([]);
|
||||
const [reverseProxyServers, setReverseProxyServers] = useState<CustomResourceSummary[]>([]);
|
||||
const [status, setStatus] = useState<K8sStatus>({ initialized: false });
|
||||
const [status, _setStatus] = useState<K8sStatus>({ initialized: false });
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const fetchData = useCallback(async () => {
|
||||
try {
|
||||
const [
|
||||
statusRes,
|
||||
podsRes,
|
||||
_statusRes,
|
||||
_podsRes,
|
||||
deploymentsRes,
|
||||
statefulSetsRes,
|
||||
servicesRes,
|
||||
@@ -47,38 +47,26 @@ export function useK8sResources() {
|
||||
|
||||
if (statefulSetsRes.status === "fulfilled" && statefulSetsRes.value.data) {
|
||||
setStatefulSets(statefulSetsRes.value.data as StatefulSetInfo[]);
|
||||
} else if (statefulSetsRes.status === "rejected") {
|
||||
console.error("Failed to fetch statefulsets:", statefulSetsRes.reason);
|
||||
}
|
||||
|
||||
if (deploymentsRes.status === "fulfilled" && deploymentsRes.value.data) {
|
||||
setDeployments(deploymentsRes.value.data as DeploymentInfo[]);
|
||||
} else if (deploymentsRes.status === "rejected") {
|
||||
console.error("Failed to fetch deployments:", deploymentsRes.reason);
|
||||
}
|
||||
|
||||
if (servicesRes.status === "fulfilled" && servicesRes.value.data) {
|
||||
setServices(servicesRes.value.data as K8sServiceSummary[]);
|
||||
} else if (servicesRes.status === "rejected") {
|
||||
console.error("Failed to fetch services:", servicesRes.reason);
|
||||
}
|
||||
|
||||
if (configMapsRes.status === "fulfilled" && configMapsRes.value.data) {
|
||||
setConfigMaps(configMapsRes.value.data as K8sConfigMapSummary[]);
|
||||
} else if (configMapsRes.status === "rejected") {
|
||||
console.error("Failed to fetch configmaps:", configMapsRes.reason);
|
||||
}
|
||||
|
||||
if (minecraftServersRes.status === "fulfilled" && minecraftServersRes.value.data) {
|
||||
setMinecraftServers(minecraftServersRes.value.data as CustomResourceSummary[]);
|
||||
} else if (minecraftServersRes.status === "rejected") {
|
||||
console.error("Failed to fetch minecraft servers:", minecraftServersRes.reason);
|
||||
}
|
||||
|
||||
if (reverseProxyServersRes.status === "fulfilled" && reverseProxyServersRes.value.data) {
|
||||
setReverseProxyServers(reverseProxyServersRes.value.data as CustomResourceSummary[]);
|
||||
} else if (reverseProxyServersRes.status === "rejected") {
|
||||
console.error("Failed to fetch reverse proxy servers:", reverseProxyServersRes.reason);
|
||||
}
|
||||
} catch (err: unknown) {
|
||||
const errorMessage =
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
|
||||
import type { NormalServer, ReverseProxyServer } from "@minikura/api";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { api } from "@/lib/api-client";
|
||||
import { getReverseProxyApi } from "@/lib/api-helpers";
|
||||
import { api } from "@/lib/api";
|
||||
|
||||
export function useServerList() {
|
||||
const [normalServers, setNormalServers] = useState<NormalServer[]>([]);
|
||||
@@ -23,8 +23,7 @@ export function useServerList() {
|
||||
if (proxyRes.data) {
|
||||
setReverseProxies(proxyRes.data as unknown as ReverseProxyServer[]);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch servers:", error);
|
||||
} catch (_error) {
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -32,17 +31,12 @@ export function useServerList() {
|
||||
|
||||
const deleteServer = useCallback(
|
||||
async (id: string, type: "normal" | "proxy") => {
|
||||
try {
|
||||
if (type === "normal") {
|
||||
await api.api.servers({ id }).delete();
|
||||
} else {
|
||||
await getReverseProxyApi()({ id }).delete();
|
||||
}
|
||||
await fetchServers();
|
||||
} catch (error) {
|
||||
console.error("Failed to delete server:", error);
|
||||
throw error;
|
||||
if (type === "normal") {
|
||||
await api.api.servers({ id }).delete();
|
||||
} else {
|
||||
await getReverseProxyApi()({ id }).delete();
|
||||
}
|
||||
await fetchServers();
|
||||
},
|
||||
[fetchServers]
|
||||
);
|
||||
|
||||
@@ -1,14 +1,9 @@
|
||||
"use client";
|
||||
|
||||
import type {
|
||||
ConnectionInfo,
|
||||
DeploymentInfo,
|
||||
PodInfo,
|
||||
StatefulSetInfo,
|
||||
} from "@minikura/api";
|
||||
import type { ConnectionInfo, DeploymentInfo, PodInfo, StatefulSetInfo } from "@minikura/api";
|
||||
import { labelKeys } from "@minikura/api";
|
||||
import { useCallback, useState } from "react";
|
||||
import { api } from "@/lib/api";
|
||||
import { api } from "@/lib/api-client";
|
||||
|
||||
export function useServerLogs(serverId: string) {
|
||||
const [pods, setPods] = useState<PodInfo[]>([]);
|
||||
@@ -23,8 +18,7 @@ export function useServerLogs(serverId: string) {
|
||||
if (response.data) {
|
||||
setPods(response.data as PodInfo[]);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch pods:", error);
|
||||
} catch (_error) {
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -42,9 +36,7 @@ export function useServerLogs(serverId: string) {
|
||||
setStatefulSetInfo(serverStatefulSet);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch StatefulSet info:", error);
|
||||
}
|
||||
} catch (_error) {}
|
||||
}, [serverId]);
|
||||
|
||||
const fetchDeploymentInfo = useCallback(async () => {
|
||||
@@ -59,9 +51,7 @@ export function useServerLogs(serverId: string) {
|
||||
setDeploymentInfo(serverDeployment);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch Deployment info:", error);
|
||||
}
|
||||
} catch (_error) {}
|
||||
}, [serverId]);
|
||||
|
||||
const fetchConnectionInfo = useCallback(async () => {
|
||||
@@ -70,9 +60,7 @@ export function useServerLogs(serverId: string) {
|
||||
if (response.data) {
|
||||
setConnectionInfo(response.data as ConnectionInfo);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch connection info:", error);
|
||||
}
|
||||
} catch (_error) {}
|
||||
}, [serverId]);
|
||||
|
||||
const refreshAll = useCallback(async () => {
|
||||
|
||||
170
apps/web/hooks/use-topology-data.ts
Normal file
170
apps/web/hooks/use-topology-data.ts
Normal file
@@ -0,0 +1,170 @@
|
||||
"use client";
|
||||
|
||||
import type { ConnectionInfo, K8sNodeSummary, PodInfo } from "@minikura/api";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { api } from "@/lib/api-client";
|
||||
import { getReverseProxyApi } from "@/lib/api-helpers";
|
||||
import type { TopologyGraph } from "@/lib/topology-types";
|
||||
import { buildTopologyGraph } from "@/lib/topology-utils";
|
||||
import { useServerList } from "./use-server-list";
|
||||
|
||||
export function useTopologyData() {
|
||||
const { normalServers, reverseProxies, loading: serversLoading } = useServerList();
|
||||
|
||||
const [graph, setGraph] = useState<TopologyGraph | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isInitialLoad, setIsInitialLoad] = useState(true);
|
||||
|
||||
const fetchTopologyData = useCallback(
|
||||
async (isRefresh = false) => {
|
||||
try {
|
||||
if (!isRefresh) {
|
||||
setLoading(true);
|
||||
}
|
||||
setError(null);
|
||||
|
||||
const nodesResponse = await api.api.k8s.nodes.get();
|
||||
const k8sNodes = (nodesResponse.data as K8sNodeSummary[]) || [];
|
||||
|
||||
const serverPodPromises = normalServers.map(async (server) => {
|
||||
try {
|
||||
const response = await api.api.k8s.servers({ serverId: server.id }).pods.get();
|
||||
return {
|
||||
serverId: server.id,
|
||||
pods: (response.data as PodInfo[]) || [],
|
||||
};
|
||||
} catch (_err) {
|
||||
return { serverId: server.id, pods: [] };
|
||||
}
|
||||
});
|
||||
|
||||
const proxyPodPromises = reverseProxies.map(async (proxy) => {
|
||||
try {
|
||||
const response = await api.api.k8s["reverse-proxy"]({
|
||||
serverId: proxy.id,
|
||||
}).pods.get();
|
||||
return {
|
||||
serverId: proxy.id,
|
||||
pods: (response.data as PodInfo[]) || [],
|
||||
};
|
||||
} catch (_err) {
|
||||
return { serverId: proxy.id, pods: [] };
|
||||
}
|
||||
});
|
||||
|
||||
const [serverPodsResults, proxyPodsResults] = await Promise.all([
|
||||
Promise.all(serverPodPromises),
|
||||
Promise.all(proxyPodPromises),
|
||||
]);
|
||||
|
||||
const serverPodsMap = new Map<string, PodInfo[]>();
|
||||
for (const result of serverPodsResults) {
|
||||
serverPodsMap.set(result.serverId, result.pods);
|
||||
}
|
||||
|
||||
const proxyPodsMap = new Map<string, PodInfo[]>();
|
||||
for (const result of proxyPodsResults) {
|
||||
proxyPodsMap.set(result.serverId, result.pods);
|
||||
}
|
||||
|
||||
const serverConnectionPromises = normalServers.map(async (server) => {
|
||||
try {
|
||||
const response = await api.api.servers({ id: server.id })["connection-info"].get();
|
||||
return {
|
||||
serverId: server.id,
|
||||
connectionInfo: response.data as ConnectionInfo,
|
||||
};
|
||||
} catch (_err) {
|
||||
return { serverId: server.id, connectionInfo: null };
|
||||
}
|
||||
});
|
||||
|
||||
const reverseProxyApi = getReverseProxyApi();
|
||||
const proxyConnectionPromises = reverseProxies.map(async (proxy) => {
|
||||
try {
|
||||
const response = await reverseProxyApi({ id: proxy.id })["connection-info"].get();
|
||||
return {
|
||||
serverId: proxy.id,
|
||||
connectionInfo: response.data as ConnectionInfo,
|
||||
};
|
||||
} catch (_err) {
|
||||
return { serverId: proxy.id, connectionInfo: null };
|
||||
}
|
||||
});
|
||||
|
||||
const [serverConnectionResults, proxyConnectionResults] = await Promise.all([
|
||||
Promise.all(serverConnectionPromises),
|
||||
Promise.all(proxyConnectionPromises),
|
||||
]);
|
||||
|
||||
const serverConnectionMap = new Map<string, ConnectionInfo | null>();
|
||||
for (const result of serverConnectionResults) {
|
||||
serverConnectionMap.set(result.serverId, result.connectionInfo);
|
||||
}
|
||||
|
||||
const proxyConnectionMap = new Map<string, ConnectionInfo | null>();
|
||||
for (const result of proxyConnectionResults) {
|
||||
proxyConnectionMap.set(result.serverId, result.connectionInfo);
|
||||
}
|
||||
|
||||
let podMetrics: any = { items: [] };
|
||||
let nodeMetrics: any = { items: [] };
|
||||
try {
|
||||
const [podMetricsRes, nodeMetricsRes] = await Promise.all([
|
||||
api.api.k8s.metrics.pods.get(),
|
||||
api.api.k8s.metrics.nodes.get(),
|
||||
]);
|
||||
podMetrics = podMetricsRes.data || { items: [] };
|
||||
nodeMetrics = nodeMetricsRes.data || { items: [] };
|
||||
} catch (_err) {}
|
||||
|
||||
const topologyGraph = buildTopologyGraph({
|
||||
servers: normalServers,
|
||||
proxies: reverseProxies,
|
||||
serverPods: serverPodsMap,
|
||||
proxyPods: proxyPodsMap,
|
||||
k8sNodes,
|
||||
serverConnections: serverConnectionMap,
|
||||
proxyConnections: proxyConnectionMap,
|
||||
podMetrics,
|
||||
nodeMetrics,
|
||||
});
|
||||
|
||||
setGraph(topologyGraph);
|
||||
setIsInitialLoad(false);
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : "Failed to fetch topology data";
|
||||
setError(errorMessage);
|
||||
} finally {
|
||||
if (!isRefresh) {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
},
|
||||
[normalServers, reverseProxies]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!serversLoading) {
|
||||
fetchTopologyData();
|
||||
}
|
||||
}, [serversLoading, fetchTopologyData]);
|
||||
|
||||
useEffect(() => {
|
||||
if (serversLoading || isInitialLoad) return;
|
||||
|
||||
const intervalId = setInterval(() => {
|
||||
fetchTopologyData(true);
|
||||
}, 5000);
|
||||
|
||||
return () => clearInterval(intervalId);
|
||||
}, [serversLoading, isInitialLoad, fetchTopologyData]);
|
||||
|
||||
return {
|
||||
graph,
|
||||
loading: loading || serversLoading,
|
||||
error,
|
||||
refresh: fetchTopologyData,
|
||||
};
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user