resource settings page
This commit is contained in:
@@ -1,8 +1,22 @@
|
||||
import { readdir } from 'node:fs/promises';
|
||||
import { readdir, mkdir } from 'node:fs/promises';
|
||||
import { existsSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { createRouter } from '../../create-router';
|
||||
import { getResourcesDir } from '../../data-path';
|
||||
|
||||
type ResourceCredentials = {
|
||||
apiKey?: string;
|
||||
username?: string;
|
||||
password?: string;
|
||||
};
|
||||
|
||||
type ResourceConnectionConfig = {
|
||||
url: string;
|
||||
credentials?: ResourceCredentials;
|
||||
};
|
||||
|
||||
type ResourcesConfig = Record<string, ResourceConnectionConfig>;
|
||||
|
||||
type Resource = {
|
||||
id: string;
|
||||
name: string;
|
||||
@@ -18,11 +32,15 @@ type Resource = {
|
||||
updateCommand: string | null;
|
||||
installed: boolean;
|
||||
version: string | null;
|
||||
connectionConfig: ResourceConnectionConfig | null;
|
||||
};
|
||||
|
||||
const stripBackticks = (value: string) => value.replace(/^`(.+)`$/, '$1');
|
||||
|
||||
function parseResourceFile(filename: string, content: string): Omit<Resource, 'installed' | 'version'> {
|
||||
function parseResourceFile(
|
||||
filename: string,
|
||||
content: string,
|
||||
): Omit<Resource, 'installed' | 'version' | 'connectionConfig'> {
|
||||
const id = filename
|
||||
.replace(/^SERVICE_/, '')
|
||||
.replace(/\.md$/, '')
|
||||
@@ -60,6 +78,23 @@ function parseResourceFile(filename: string, content: string): Omit<Resource, 'i
|
||||
};
|
||||
}
|
||||
|
||||
const CONFIG_FILENAME = 'resources-config.json';
|
||||
|
||||
const getConfigPath = () => join(getResourcesDir(), CONFIG_FILENAME);
|
||||
|
||||
async function readConfig(): Promise<ResourcesConfig> {
|
||||
const path = getConfigPath();
|
||||
if (!existsSync(path)) return {};
|
||||
const text = await Bun.file(path).text();
|
||||
return JSON.parse(text) as ResourcesConfig;
|
||||
}
|
||||
|
||||
async function writeConfig(config: ResourcesConfig): Promise<void> {
|
||||
const dir = getResourcesDir();
|
||||
if (!existsSync(dir)) await mkdir(dir, { recursive: true });
|
||||
await Bun.write(getConfigPath(), JSON.stringify(config, null, 2));
|
||||
}
|
||||
|
||||
const CHECK_TIMEOUT_MS = 3_000;
|
||||
|
||||
async function checkPort(port: number): Promise<boolean> {
|
||||
@@ -107,14 +142,36 @@ function extractFirstPort(portStr: string): number | null {
|
||||
return match ? parseInt(match[1]!, 10) : null;
|
||||
}
|
||||
|
||||
async function checkResourceStatus(
|
||||
resource: Omit<Resource, 'installed' | 'version'>,
|
||||
): Promise<{ installed: boolean; version: string | null }> {
|
||||
async function checkUrl(url: string): Promise<boolean> {
|
||||
try {
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), CHECK_TIMEOUT_MS);
|
||||
await fetch(url, { signal: controller.signal });
|
||||
clearTimeout(timeout);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
type CheckResourceStatusParams = {
|
||||
resource: Omit<Resource, 'installed' | 'version' | 'connectionConfig'>;
|
||||
configUrl?: string;
|
||||
};
|
||||
|
||||
async function checkResourceStatus({
|
||||
resource,
|
||||
configUrl,
|
||||
}: CheckResourceStatusParams): Promise<{ installed: boolean; version: string | null }> {
|
||||
if (resource.path) {
|
||||
const fullPath = `${getResourcesDir()}/${resource.path}`;
|
||||
return { installed: existsSync(fullPath), version: null };
|
||||
}
|
||||
if (resource.port) {
|
||||
if (configUrl) {
|
||||
const reachable = await checkUrl(configUrl);
|
||||
if (reachable) return { installed: true, version: null };
|
||||
}
|
||||
const port = extractFirstPort(resource.port);
|
||||
if (port) {
|
||||
const reachable = await checkPort(port);
|
||||
@@ -127,10 +184,20 @@ async function checkResourceStatus(
|
||||
return { installed: false, version: null };
|
||||
}
|
||||
|
||||
function buildConnectionConfig(
|
||||
resource: Omit<Resource, 'installed' | 'version' | 'connectionConfig'>,
|
||||
config: ResourcesConfig,
|
||||
): ResourceConnectionConfig | null {
|
||||
if (!resource.port) return null;
|
||||
if (config[resource.id]) return config[resource.id]!;
|
||||
const port = extractFirstPort(resource.port);
|
||||
return { url: `http://127.0.0.1:${port ?? resource.port}` };
|
||||
}
|
||||
|
||||
async function loadResources(): Promise<Resource[]> {
|
||||
const dir = getResourcesDir();
|
||||
if (!existsSync(dir)) return [];
|
||||
const files = await readdir(dir);
|
||||
const [files, config] = await Promise.all([readdir(dir), readConfig()]);
|
||||
const serviceFiles = files.filter((f) => f.startsWith('SERVICE_') && f.endsWith('.md'));
|
||||
|
||||
const parsed = await Promise.all(
|
||||
@@ -142,8 +209,10 @@ async function loadResources(): Promise<Resource[]> {
|
||||
|
||||
const resources = await Promise.all(
|
||||
parsed.map(async (r) => {
|
||||
const status = await checkResourceStatus(r);
|
||||
return { ...r, ...status };
|
||||
const configUrl = config[r.id]?.url;
|
||||
const status = await checkResourceStatus({ resource: r, configUrl });
|
||||
const connectionConfig = buildConnectionConfig(r, config);
|
||||
return { ...r, ...status, connectionConfig };
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -157,6 +226,45 @@ resourcesRouter.get('/', async (ctx) => {
|
||||
return ctx.json(resources);
|
||||
});
|
||||
|
||||
resourcesRouter.get('/config', async (ctx) => {
|
||||
const config = await readConfig();
|
||||
return ctx.json(config);
|
||||
});
|
||||
|
||||
resourcesRouter.patch('/config/:id', async (ctx) => {
|
||||
const id = ctx.req.param('id');
|
||||
const body = await ctx.req.json<Partial<ResourceConnectionConfig>>();
|
||||
const config = await readConfig();
|
||||
const existing = config[id] ?? { url: '' };
|
||||
config[id] = { ...existing, ...body };
|
||||
await writeConfig(config);
|
||||
return ctx.json(config[id]);
|
||||
});
|
||||
|
||||
resourcesRouter.post('/:id/ping', async (ctx) => {
|
||||
const id = ctx.req.param('id');
|
||||
const body = await ctx.req.json<{ url?: string }>().catch((): { url?: string } => ({}));
|
||||
const config = await readConfig();
|
||||
const resources = await loadResources();
|
||||
const resource = resources.find((r) => r.id === id);
|
||||
if (!resource) return ctx.json({ error: 'Resource not found' }, 404);
|
||||
|
||||
const url = body.url ?? config[id]?.url ?? resource.connectionConfig?.url;
|
||||
if (!url) return ctx.json({ error: 'No URL configured' }, 400);
|
||||
|
||||
try {
|
||||
const start = performance.now();
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), CHECK_TIMEOUT_MS);
|
||||
await fetch(url, { signal: controller.signal });
|
||||
clearTimeout(timeout);
|
||||
const latencyMs = Math.round(performance.now() - start);
|
||||
return ctx.json({ reachable: true, latencyMs });
|
||||
} catch {
|
||||
return ctx.json({ reachable: false, latencyMs: null });
|
||||
}
|
||||
});
|
||||
|
||||
resourcesRouter.get('/:id', async (ctx) => {
|
||||
const resources = await loadResources();
|
||||
const resource = resources.find((r) => r.id === ctx.req.param('id'));
|
||||
|
||||
Reference in New Issue
Block a user