2023-06-14 17:31:52 +09:00
|
|
|
import { TRPCError } from '@trpc/server';
|
2023-06-10 10:23:54 +02:00
|
|
|
import axios, { AxiosError } from 'axios';
|
|
|
|
|
import Consola from 'consola';
|
2023-06-14 17:31:52 +09:00
|
|
|
import https from 'https';
|
|
|
|
|
import { z } from 'zod';
|
2023-07-22 18:27:24 +02:00
|
|
|
import { isStatusOk } from '~/components/Dashboard/Tiles/Apps/AppPing';
|
2023-06-14 17:31:52 +09:00
|
|
|
import { getConfig } from '~/tools/config/getConfig';
|
|
|
|
|
import { AppType } from '~/types/app';
|
|
|
|
|
|
2023-06-10 10:23:54 +02:00
|
|
|
import { createTRPCRouter, publicProcedure } from '../trpc';
|
|
|
|
|
|
|
|
|
|
export const appRouter = createTRPCRouter({
|
2023-10-25 15:29:45 +02:00
|
|
|
ping: publicProcedure
|
|
|
|
|
.input(
|
|
|
|
|
z.object({
|
|
|
|
|
id: z.string(),
|
|
|
|
|
configName: z.string(),
|
|
|
|
|
})
|
|
|
|
|
)
|
|
|
|
|
.query(async ({ input }) => {
|
|
|
|
|
const agent = new https.Agent({ rejectUnauthorized: false });
|
|
|
|
|
const config = getConfig(input.configName);
|
|
|
|
|
const app = config.apps.find((app) => app.id === input.id);
|
2023-07-17 21:35:34 +02:00
|
|
|
|
2023-10-25 15:29:45 +02:00
|
|
|
if (!app?.url) {
|
|
|
|
|
Consola.error(`App ${input} not found`);
|
|
|
|
|
throw new TRPCError({
|
|
|
|
|
code: 'NOT_FOUND',
|
|
|
|
|
cause: input,
|
|
|
|
|
message: `App ${input.id} was not found`,
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
const res = await axios
|
|
|
|
|
.get(app.url, { httpsAgent: agent, timeout: 10000 })
|
|
|
|
|
.then((response) => ({
|
|
|
|
|
status: response.status,
|
|
|
|
|
statusText: response.statusText,
|
|
|
|
|
state: isStatusOk(app as AppType, response.status) ? 'online' : 'offline',
|
|
|
|
|
}))
|
|
|
|
|
.catch((error: AxiosError) => {
|
|
|
|
|
if (error.response) {
|
|
|
|
|
return {
|
|
|
|
|
state: isStatusOk(app as AppType, error.response.status) ? 'online' : 'offline',
|
|
|
|
|
status: error.response.status,
|
|
|
|
|
statusText: error.response.statusText,
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (error.code === 'ECONNABORTED') {
|
|
|
|
|
Consola.error(
|
|
|
|
|
`Ping timed out for app with id '${input.id}' in config '${input.configName}' -> url: ${app.url})`
|
|
|
|
|
);
|
|
|
|
|
throw new TRPCError({
|
|
|
|
|
code: 'TIMEOUT',
|
|
|
|
|
cause: input,
|
|
|
|
|
message: `Ping timed out`,
|
|
|
|
|
});
|
|
|
|
|
}
|
2023-07-17 21:35:34 +02:00
|
|
|
|
2023-10-25 15:29:45 +02:00
|
|
|
Consola.error(`Unexpected response: ${error.message}`);
|
2023-07-22 10:11:23 +09:00
|
|
|
throw new TRPCError({
|
2023-10-25 15:29:45 +02:00
|
|
|
code: 'UNPROCESSABLE_CONTENT',
|
2023-07-22 10:11:23 +09:00
|
|
|
cause: input,
|
2023-10-25 15:29:45 +02:00
|
|
|
message: `Unexpected response: ${error.message}`,
|
2023-07-22 10:11:23 +09:00
|
|
|
});
|
|
|
|
|
});
|
2023-10-25 15:29:45 +02:00
|
|
|
return res;
|
|
|
|
|
}),
|
2023-06-10 10:23:54 +02:00
|
|
|
});
|