Compare commits
43
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c27393942e | ||
|
|
d1077a1314 | ||
|
|
22bcb74653 | ||
|
|
78f5ce180b | ||
|
|
a9e9097a1f | ||
|
|
be1ca4ac28 | ||
|
|
7a0e0bccf4 | ||
|
|
01401d56b8 | ||
|
|
f69b7f6a35 | ||
|
|
cb5316e6f5 | ||
|
|
25baff3013 | ||
|
|
85d2d34a90 | ||
|
|
f6d9b7566b | ||
|
|
84cac870d5 | ||
|
|
2884ab524d | ||
|
|
eac470cb68 | ||
|
|
a15b9837c6 | ||
|
|
562d723fcf | ||
|
|
2fdd5a72f0 | ||
|
|
3e26387b9d | ||
|
|
dc7d442ace | ||
|
|
839f1beb41 | ||
|
|
bbdadb0bf5 | ||
|
|
cadf68740a | ||
|
|
6ad0a6a29d | ||
|
|
77af9d2e93 | ||
|
|
b1147b8bf9 | ||
|
|
5ab230f77b | ||
|
|
d9cb81e71d | ||
|
|
0058772f61 | ||
|
|
bbc2e4073b | ||
|
|
7967b363c2 | ||
|
|
27dffe9fa6 | ||
|
|
7213bace08 | ||
|
|
2cbc667f30 | ||
|
|
978dc4cda6 | ||
|
|
a960e3aba2 | ||
|
|
08fd09f59b | ||
|
|
6c421717f8 | ||
|
|
083db95151 | ||
|
|
b11ba68ff8 | ||
|
|
12a4112055 | ||
|
|
33201096b7 |
No files matched your search
@@ -46,11 +46,11 @@ You can see the latest build of [Checkmate](https://checkmate-demo.bluewavelabs.
|
|||||||
|
|
||||||
## User's guide
|
## User's guide
|
||||||
|
|
||||||
Usage instructions can be found [here](https://docs.checkmate.so/checkmate-2.1). It's still WIP and some of the information there might be outdated as we continuously add features weekly. Rest assured, we are doing our best! :)
|
Usage instructions can be found [here](https://checkmate.so/docs).
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
See installation instructions in [Checkmate documentation portal](https://docs.checkmate.so/checkmate-2.1/users-guide/quickstart).
|
See installation instructions in [Checkmate documentation portal](https://checkmate.so/docs).
|
||||||
|
|
||||||
Alternatively, you can also use [Elestio](https://elest.io/open-source/checkmate), [K8s](./charts/helm/checkmate/INSTALLATION.md), [Sive Host](https://sive.host) (South Africa) or [Pikapods](https://www.pikapods.com/) to quickly spin off a Checkmate instance. If you would like to monitor your server infrastructure, you'll need [Capture agent](https://github.com/bluewave-labs/capture). Capture repository also contains the installation instructions.
|
Alternatively, you can also use [Elestio](https://elest.io/open-source/checkmate), [K8s](./charts/helm/checkmate/INSTALLATION.md), [Sive Host](https://sive.host) (South Africa) or [Pikapods](https://www.pikapods.com/) to quickly spin off a Checkmate instance. If you would like to monitor your server infrastructure, you'll need [Capture agent](https://github.com/bluewave-labs/capture). Capture repository also contains the installation instructions.
|
||||||
|
|
||||||
@@ -157,12 +157,11 @@ Here's how you can contribute:
|
|||||||
|
|
||||||
0. Star this repo :)
|
0. Star this repo :)
|
||||||
1. Check [Contributor's guideline](https://github.com/bluewave-labs/Checkmate/blob/develop/CONTRIBUTING.md). First timers are encouraged to check `good-first-issue` tag.
|
1. Check [Contributor's guideline](https://github.com/bluewave-labs/Checkmate/blob/develop/CONTRIBUTING.md). First timers are encouraged to check `good-first-issue` tag.
|
||||||
2. Check [project structure](https://docs.checkmate.so/checkmate-2.1/developers-guide/general-project-structure) and [high level overview](https://bluewavelabs.gitbook.io/checkmate/developers-guide/high-level-overview).
|
2. Read a detailed structure of [Checkmate](https://deepwiki.com/bluewave-labs/Checkmate) if you would like to deep dive into the architecture.
|
||||||
3. Read a detailed structure of [Checkmate](https://deepwiki.com/bluewave-labs/Checkmate) if you would like to deep dive into the architecture.
|
3. Open an issue if you believe you've encountered a bug.
|
||||||
4. Open an issue if you believe you've encountered a bug.
|
4. Check for good-first-issue's if you are a newcomer.
|
||||||
5. Check for good-first-issue's if you are a newcomer.
|
5. Make a pull request to add new features/make quality-of-life improvements/fix bugs.
|
||||||
6. Make a pull request to add new features/make quality-of-life improvements/fix bugs.
|
6. Check out this interactive walkthrough of the `Checkmate` codebase on CodeCanvas [here](https://www.code-canvas.com/?session=unauthenticatedGithub&repo=Checkmate&owner=bluewave-labs&branch=develop&OnboardingTutorial=true). To refine existing dataflow simulation or create new ones, follow the quick tutorial [here](https://docs.code-canvas.com/updating-diagram).
|
||||||
7. Check out this interactive walkthrough of the `Checkmate` codebase on CodeCanvas [here](https://www.code-canvas.com/?session=unauthenticatedGithub&repo=Checkmate&owner=bluewave-labs&branch=develop&OnboardingTutorial=true). To refine existing dataflow simulation or create new ones, follow the quick tutorial [here](https://docs.code-canvas.com/updating-diagram).
|
|
||||||
|
|
||||||
<a href="https://github.com/bluewave-labs/checkmate/graphs/contributors">
|
<a href="https://github.com/bluewave-labs/checkmate/graphs/contributors">
|
||||||
<img src="https://contrib.rocks/image?repo=bluewave-labs/checkmate" />
|
<img src="https://contrib.rocks/image?repo=bluewave-labs/checkmate" />
|
||||||
@@ -175,9 +174,3 @@ Here's how you can contribute:
|
|||||||
Thanks to [Gitbook](https://gitbook.io/) for giving us a free tier for their documentation platform, and [Poeditor](https://poeditor.com/) providing us a free account to use their i18n services. If you would like to sponsor Checkmate, please send an email to hello@bluewavelabs.ca
|
Thanks to [Gitbook](https://gitbook.io/) for giving us a free tier for their documentation platform, and [Poeditor](https://poeditor.com/) providing us a free account to use their i18n services. If you would like to sponsor Checkmate, please send an email to hello@bluewavelabs.ca
|
||||||
|
|
||||||
If you would like to sponsor a feature, [see this page](https://checkmate.so/sponsored-features).
|
If you would like to sponsor a feature, [see this page](https://checkmate.so/sponsored-features).
|
||||||
|
|
||||||
Also check other developer and contributor-friendly projects of BlueWave:
|
|
||||||
|
|
||||||
- [VerifyWise](https://github.com/bluewave-labs/verifywise), the first open source AI governance platform.
|
|
||||||
- [DataRoom](https://github.com/bluewave-labs/bluewave-dataroom), an secure file sharing application, aka dataroom.
|
|
||||||
- [Guidefox](https://github.com/bluewave-labs/guidefox), an application that helps new users learn how to use your product via hints, tours, popups and banners.
|
|
||||||
@@ -11,20 +11,26 @@ import type { ResponsiveStyleValue } from "@mui/system";
|
|||||||
interface SliderInputProps extends SliderProps {
|
interface SliderInputProps extends SliderProps {
|
||||||
sx?: SliderProps["sx"];
|
sx?: SliderProps["sx"];
|
||||||
showValue?: boolean;
|
showValue?: boolean;
|
||||||
|
formatDisplayValue?: (value: number) => string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const SliderInput = forwardRef<HTMLSpanElement, SliderInputProps>(
|
export const SliderInput = forwardRef<HTMLSpanElement, SliderInputProps>(
|
||||||
({ sx, showValue = false, ...props }, ref) => {
|
({ sx, showValue = false, formatDisplayValue, ...props }, ref) => {
|
||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
const additionalSx = Array.isArray(sx) ? sx : sx ? [sx] : [];
|
const additionalSx = Array.isArray(sx) ? sx : sx ? [sx] : [];
|
||||||
|
|
||||||
|
const displayValue =
|
||||||
|
showValue && formatDisplayValue && typeof props.value === "number"
|
||||||
|
? formatDisplayValue(props.value)
|
||||||
|
: props.value;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Stack
|
<Stack
|
||||||
gap={theme.spacing(8)}
|
gap={theme.spacing(8)}
|
||||||
direction={"row"}
|
direction={"row"}
|
||||||
alignItems={"center"}
|
alignItems={"center"}
|
||||||
>
|
>
|
||||||
{showValue && <Typography>{props.value}</Typography>}
|
{showValue && <Typography>{displayValue}</Typography>}
|
||||||
<Slider
|
<Slider
|
||||||
{...props}
|
{...props}
|
||||||
ref={ref}
|
ref={ref}
|
||||||
@@ -63,12 +69,21 @@ interface SliderWithLabelProps extends SliderProps {
|
|||||||
fieldLabel?: string;
|
fieldLabel?: string;
|
||||||
required?: boolean;
|
required?: boolean;
|
||||||
showValue?: boolean;
|
showValue?: boolean;
|
||||||
|
formatDisplayValue?: (value: number) => string;
|
||||||
sliderMaxWidth?: ResponsiveStyleValue<number | string>;
|
sliderMaxWidth?: ResponsiveStyleValue<number | string>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const SliderWithLabel = forwardRef<HTMLSpanElement, SliderWithLabelProps>(
|
export const SliderWithLabel = forwardRef<HTMLSpanElement, SliderWithLabelProps>(
|
||||||
(
|
(
|
||||||
{ fieldLabel, required, showValue = true, value, sliderMaxWidth = "100%", ...props },
|
{
|
||||||
|
fieldLabel,
|
||||||
|
required,
|
||||||
|
showValue = true,
|
||||||
|
formatDisplayValue,
|
||||||
|
value,
|
||||||
|
sliderMaxWidth = "100%",
|
||||||
|
...props
|
||||||
|
},
|
||||||
ref
|
ref
|
||||||
) => {
|
) => {
|
||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
@@ -82,6 +97,7 @@ export const SliderWithLabel = forwardRef<HTMLSpanElement, SliderWithLabelProps>
|
|||||||
<SliderInput
|
<SliderInput
|
||||||
{...props}
|
{...props}
|
||||||
showValue={showValue}
|
showValue={showValue}
|
||||||
|
formatDisplayValue={formatDisplayValue}
|
||||||
value={value}
|
value={value}
|
||||||
ref={ref}
|
ref={ref}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -27,12 +27,14 @@ export const useStatusPageForm = ({
|
|||||||
companyName: data?.companyName || "",
|
companyName: data?.companyName || "",
|
||||||
url: data?.url || generateDefaultUrl(),
|
url: data?.url || generateDefaultUrl(),
|
||||||
timezone: data?.timezone || Intl.DateTimeFormat().resolvedOptions().timeZone,
|
timezone: data?.timezone || Intl.DateTimeFormat().resolvedOptions().timeZone,
|
||||||
|
type: data?.type || ["uptime"],
|
||||||
color: data?.color || "#4169E1",
|
color: data?.color || "#4169E1",
|
||||||
monitors: data?.monitors || [],
|
monitors: data?.monitors || [],
|
||||||
isPublished: data?.isPublished ?? false,
|
isPublished: data?.isPublished ?? false,
|
||||||
showCharts: data?.showCharts ?? true,
|
showCharts: data?.showCharts ?? true,
|
||||||
showUptimePercentage: data?.showUptimePercentage ?? true,
|
showUptimePercentage: data?.showUptimePercentage ?? true,
|
||||||
showAdminLoginLink: data?.showAdminLoginLink ?? false,
|
showAdminLoginLink: data?.showAdminLoginLink ?? false,
|
||||||
|
showInfrastructure: data?.showInfrastructure ?? false,
|
||||||
customCSS: data?.customCSS || "",
|
customCSS: data?.customCSS || "",
|
||||||
logo: transformLogo(data?.logo),
|
logo: transformLogo(data?.logo),
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -302,49 +302,49 @@ const CreateMonitorPage = () => {
|
|||||||
>
|
>
|
||||||
<RadioWithDescription
|
<RadioWithDescription
|
||||||
value="http"
|
value="http"
|
||||||
label={t("pages.createMonitor.form.type.optionHttp")}
|
label={t("pages.common.monitors.monitorTypes.optionHttp")}
|
||||||
description={t(
|
description={t(
|
||||||
"pages.createMonitor.form.type.optionHttpDescription"
|
"pages.createMonitor.form.type.optionHttpDescription"
|
||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
<RadioWithDescription
|
<RadioWithDescription
|
||||||
value="ping"
|
value="ping"
|
||||||
label={t("pages.createMonitor.form.type.optionPing")}
|
label={t("pages.common.monitors.monitorTypes.optionPing")}
|
||||||
description={t(
|
description={t(
|
||||||
"pages.createMonitor.form.type.optionPingDescription"
|
"pages.createMonitor.form.type.optionPingDescription"
|
||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
<RadioWithDescription
|
<RadioWithDescription
|
||||||
value="docker"
|
value="docker"
|
||||||
label={t("pages.createMonitor.form.type.optionDocker")}
|
label={t("pages.common.monitors.monitorTypes.optionDocker")}
|
||||||
description={t(
|
description={t(
|
||||||
"pages.createMonitor.form.type.optionDockerDescription"
|
"pages.createMonitor.form.type.optionDockerDescription"
|
||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
<RadioWithDescription
|
<RadioWithDescription
|
||||||
value="port"
|
value="port"
|
||||||
label={t("pages.createMonitor.form.type.optionPort")}
|
label={t("pages.common.monitors.monitorTypes.optionPort")}
|
||||||
description={t(
|
description={t(
|
||||||
"pages.createMonitor.form.type.optionPortDescription"
|
"pages.createMonitor.form.type.optionPortDescription"
|
||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
<RadioWithDescription
|
<RadioWithDescription
|
||||||
value="game"
|
value="game"
|
||||||
label={t("pages.createMonitor.form.type.optionGame")}
|
label={t("pages.common.monitors.monitorTypes.optionGame")}
|
||||||
description={t(
|
description={t(
|
||||||
"pages.createMonitor.form.type.optionGameDescription"
|
"pages.createMonitor.form.type.optionGameDescription"
|
||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
<RadioWithDescription
|
<RadioWithDescription
|
||||||
value="grpc"
|
value="grpc"
|
||||||
label={t("pages.createMonitor.form.type.optionGrpc")}
|
label={t("pages.common.monitors.monitorTypes.optionGrpc")}
|
||||||
description={t(
|
description={t(
|
||||||
"pages.createMonitor.form.type.optionGrpcDescription"
|
"pages.createMonitor.form.type.optionGrpcDescription"
|
||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
<RadioWithDescription
|
<RadioWithDescription
|
||||||
value="websocket"
|
value="websocket"
|
||||||
label={t("pages.createMonitor.form.type.optionWebSocket")}
|
label={t("pages.common.monitors.monitorTypes.optionWebSocket")}
|
||||||
description={t(
|
description={t(
|
||||||
"pages.createMonitor.form.type.optionWebSocketDescription"
|
"pages.createMonitor.form.type.optionWebSocketDescription"
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -37,6 +37,7 @@ import {
|
|||||||
} from "@/Features/UI/uiSlice.js";
|
} from "@/Features/UI/uiSlice.js";
|
||||||
import timezones from "@/Utils/timezones.json";
|
import timezones from "@/Utils/timezones.json";
|
||||||
import type { RootState } from "@/Types/state";
|
import type { RootState } from "@/Types/state";
|
||||||
|
import { CHECK_TTL_SENTINEL } from "@/Types/Check";
|
||||||
|
|
||||||
interface Timezone {
|
interface Timezone {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -462,6 +463,43 @@ export const SettingsPage = () => {
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* Check Retention */}
|
||||||
|
{isAdmin && (
|
||||||
|
<ConfigBox
|
||||||
|
title={t("pages.settings.form.retention.title")}
|
||||||
|
subtitle={t("pages.settings.form.retention.description")}
|
||||||
|
rightContent={
|
||||||
|
<Controller
|
||||||
|
name="checkTTL"
|
||||||
|
control={form.control}
|
||||||
|
defaultValue={defaults.checkTTL}
|
||||||
|
render={({ field }) => (
|
||||||
|
<SliderWithLabel
|
||||||
|
{...field}
|
||||||
|
fieldLabel={t("pages.settings.form.retention.option.days.label")}
|
||||||
|
min={1}
|
||||||
|
max={CHECK_TTL_SENTINEL}
|
||||||
|
sliderMaxWidth={{ xs: "100%", md: "50%" }}
|
||||||
|
value={field.value || 30}
|
||||||
|
onChange={(_, value) => field.onChange(value)}
|
||||||
|
valueLabelDisplay="auto"
|
||||||
|
valueLabelFormat={(value: number) =>
|
||||||
|
value >= CHECK_TTL_SENTINEL
|
||||||
|
? t("pages.settings.form.retention.option.days.unlimited")
|
||||||
|
: `${value}`
|
||||||
|
}
|
||||||
|
formatDisplayValue={(value: number) =>
|
||||||
|
value >= CHECK_TTL_SENTINEL
|
||||||
|
? t("pages.settings.form.retention.option.days.unlimited")
|
||||||
|
: `${value}`
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* Global Thresholds */}
|
{/* Global Thresholds */}
|
||||||
{isAdmin && (
|
{isAdmin && (
|
||||||
<ConfigBox
|
<ConfigBox
|
||||||
|
|||||||
@@ -21,14 +21,14 @@ import {
|
|||||||
|
|
||||||
import { useTheme } from "@mui/material/styles";
|
import { useTheme } from "@mui/material/styles";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useMemo, useState } from "react";
|
||||||
import { useForm, Controller } from "react-hook-form";
|
import { useForm, Controller } from "react-hook-form";
|
||||||
import { zodResolver } from "@hookform/resolvers/zod";
|
import { zodResolver } from "@hookform/resolvers/zod";
|
||||||
import { useStatusPageForm } from "@/Hooks/useStatusPageForm";
|
import { useStatusPageForm } from "@/Hooks/useStatusPageForm";
|
||||||
import type { StatusPageFormData } from "@/Validation/statusPage";
|
import type { StatusPageFormData } from "@/Validation/statusPage";
|
||||||
import { useGet, usePost, usePut, useDelete } from "@/Hooks/UseApi";
|
import { useGet, usePost, usePut, useDelete } from "@/Hooks/UseApi";
|
||||||
import type { Monitor } from "@/Types/Monitor";
|
import type { Monitor } from "@/Types/Monitor";
|
||||||
import type { StatusPageResponse } from "@/Types/StatusPage";
|
import type { MonitorDisplayType, StatusPageResponse } from "@/Types/StatusPage";
|
||||||
import timezones from "@/Utils/timezones.json";
|
import timezones from "@/Utils/timezones.json";
|
||||||
import { useNavigate, useParams } from "react-router-dom";
|
import { useNavigate, useParams } from "react-router-dom";
|
||||||
import axios from "axios";
|
import axios from "axios";
|
||||||
@@ -39,6 +39,22 @@ interface TimezoneOption {
|
|||||||
name: string;
|
name: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const MONITOR_TYPE_KEYS: Record<string, string> = {
|
||||||
|
http: "pages.common.monitors.monitorTypes.optionHttp",
|
||||||
|
ping: "pages.common.monitors.monitorTypes.optionPing",
|
||||||
|
docker: "pages.common.monitors.monitorTypes.optionDocker",
|
||||||
|
port: "pages.common.monitors.monitorTypes.optionPort",
|
||||||
|
game: "pages.common.monitors.monitorTypes.optionGame",
|
||||||
|
grpc: "pages.common.monitors.monitorTypes.optionGrpc",
|
||||||
|
websocket: "pages.common.monitors.monitorTypes.optionWebSocket",
|
||||||
|
hardware: "pages.common.monitors.monitorTypes.optionHardware",
|
||||||
|
};
|
||||||
|
|
||||||
|
const getMonitorTypeLabel = (type: string, t: (key: string) => string): string => {
|
||||||
|
const i18nMonitorKey = MONITOR_TYPE_KEYS[type];
|
||||||
|
return i18nMonitorKey ? t(i18nMonitorKey) : type;
|
||||||
|
};
|
||||||
|
|
||||||
const CreateStatusPage = () => {
|
const CreateStatusPage = () => {
|
||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
@@ -49,10 +65,12 @@ const CreateStatusPage = () => {
|
|||||||
|
|
||||||
// Fetch existing status page data when configuring
|
// Fetch existing status page data when configuring
|
||||||
const { data: statusPageData, isLoading: isLoadingStatusPage } =
|
const { data: statusPageData, isLoading: isLoadingStatusPage } =
|
||||||
useGet<StatusPageResponse>(isCreate ? null : `/status-page/${url}?type=uptime`);
|
useGet<StatusPageResponse>(
|
||||||
|
isCreate ? null : `/status-page/${url}?type=uptime&type=infrastructure`
|
||||||
|
);
|
||||||
|
|
||||||
const { data: monitorsResponse } = useGet<Monitor[]>(
|
const { data: monitorsResponse } = useGet<Monitor[]>(
|
||||||
"/monitors/team?type=http&type=ping&type=port&type=docker"
|
"/monitors/team?type=http&type=ping&type=port&type=docker&type=hardware"
|
||||||
);
|
);
|
||||||
const monitors = monitorsResponse ?? [];
|
const monitors = monitorsResponse ?? [];
|
||||||
|
|
||||||
@@ -81,6 +99,24 @@ const CreateStatusPage = () => {
|
|||||||
reset(defaults);
|
reset(defaults);
|
||||||
}, [defaults, reset]);
|
}, [defaults, reset]);
|
||||||
|
|
||||||
|
const watchedMonitorIds: string[] = form.watch("monitors") ?? [];
|
||||||
|
const computedTypes: MonitorDisplayType[] = useMemo(() => {
|
||||||
|
const selectedMonitors = (watchedMonitorIds ?? [])
|
||||||
|
.map((id) => monitors.find((m) => m.id === id))
|
||||||
|
.filter((m): m is Monitor => m !== undefined);
|
||||||
|
|
||||||
|
const typesSet = new Set<MonitorDisplayType>();
|
||||||
|
selectedMonitors.forEach((m) => {
|
||||||
|
typesSet.add(m.type === "hardware" ? "infrastructure" : "uptime");
|
||||||
|
});
|
||||||
|
|
||||||
|
return typesSet.size ? Array.from(typesSet) : ["uptime"];
|
||||||
|
}, [JSON.stringify(watchedMonitorIds), monitors]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
form.setValue("type", computedTypes);
|
||||||
|
}, [computedTypes]);
|
||||||
|
|
||||||
const onError = (errors: any) => {
|
const onError = (errors: any) => {
|
||||||
logger.debug("Status page validation errors", errors);
|
logger.debug("Status page validation errors", errors);
|
||||||
};
|
};
|
||||||
@@ -103,7 +139,6 @@ const CreateStatusPage = () => {
|
|||||||
|
|
||||||
const onSubmit = async (data: StatusPageFormData) => {
|
const onSubmit = async (data: StatusPageFormData) => {
|
||||||
const fd = new FormData();
|
const fd = new FormData();
|
||||||
fd.append("type", "uptime");
|
|
||||||
fd.append("isPublished", String(data.isPublished));
|
fd.append("isPublished", String(data.isPublished));
|
||||||
if (data.companyName) fd.append("companyName", data.companyName);
|
if (data.companyName) fd.append("companyName", data.companyName);
|
||||||
if (data.url) fd.append("url", data.url);
|
if (data.url) fd.append("url", data.url);
|
||||||
@@ -112,11 +147,16 @@ const CreateStatusPage = () => {
|
|||||||
fd.append("showCharts", String(data.showCharts));
|
fd.append("showCharts", String(data.showCharts));
|
||||||
fd.append("showUptimePercentage", String(data.showUptimePercentage));
|
fd.append("showUptimePercentage", String(data.showUptimePercentage));
|
||||||
fd.append("showAdminLoginLink", String(data.showAdminLoginLink));
|
fd.append("showAdminLoginLink", String(data.showAdminLoginLink));
|
||||||
|
fd.append("showInfrastructure", String(data.showInfrastructure));
|
||||||
|
|
||||||
data.monitors.forEach((monitorId) => {
|
data.monitors.forEach((monitorId) => {
|
||||||
fd.append("monitors[]", monitorId);
|
fd.append("monitors[]", monitorId);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
data.type.forEach((type) => {
|
||||||
|
fd.append("type[]", type);
|
||||||
|
});
|
||||||
|
|
||||||
// Handle logo upload
|
// Handle logo upload
|
||||||
if (data.logo === null) {
|
if (data.logo === null) {
|
||||||
// Signal to remove the logo
|
// Signal to remove the logo
|
||||||
@@ -303,7 +343,9 @@ const CreateStatusPage = () => {
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<GripVertical size={20} />
|
<GripVertical size={20} />
|
||||||
<Typography flexGrow={1}>{monitor.name}</Typography>
|
<Typography
|
||||||
|
flexGrow={1}
|
||||||
|
>{`${monitor.name} (${getMonitorTypeLabel(monitor.type, t)})`}</Typography>
|
||||||
<IconButton
|
<IconButton
|
||||||
size="small"
|
size="small"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
@@ -425,6 +467,23 @@ const CreateStatusPage = () => {
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
|
<Controller
|
||||||
|
name="showInfrastructure"
|
||||||
|
control={control}
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormControlLabel
|
||||||
|
control={
|
||||||
|
<Checkbox
|
||||||
|
checked={field.value}
|
||||||
|
onChange={field.onChange}
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
label={t(
|
||||||
|
"pages.statusPages.form.features.option.showInfrastructure.label"
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
{/* <Controller
|
{/* <Controller
|
||||||
name="showUptimePercentage"
|
name="showUptimePercentage"
|
||||||
control={control}
|
control={control}
|
||||||
|
|||||||
@@ -0,0 +1,246 @@
|
|||||||
|
import Stack from "@mui/material/Stack";
|
||||||
|
import Typography from "@mui/material/Typography";
|
||||||
|
import { Gauge } from "@/Components/design-elements";
|
||||||
|
import { useTheme } from "@mui/material/styles";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import prettyBytes from "pretty-bytes";
|
||||||
|
import type { Monitor } from "@/Types/Monitor";
|
||||||
|
import Grid from "@mui/material/Grid";
|
||||||
|
import useMediaQuery from "@mui/material/useMediaQuery";
|
||||||
|
import Box from "@mui/material/Box";
|
||||||
|
import { LAYOUT, SPACING } from "@/Utils/Theme/constants";
|
||||||
|
|
||||||
|
const GAUGE_RADIUS = 60;
|
||||||
|
const GAUGE_STROKE_WIDTH = 12;
|
||||||
|
const PERCENTAGE_MULTIPLIER = 100;
|
||||||
|
|
||||||
|
interface StatusPageMonitor extends Monitor {
|
||||||
|
checks?: Monitor["recentChecks"];
|
||||||
|
}
|
||||||
|
|
||||||
|
interface MetricDetail {
|
||||||
|
label: string;
|
||||||
|
value: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface MetricConfig {
|
||||||
|
key: string;
|
||||||
|
label: string;
|
||||||
|
hasData: boolean;
|
||||||
|
progress: number;
|
||||||
|
details: MetricDetail[];
|
||||||
|
}
|
||||||
|
|
||||||
|
const MetricDetailRow = ({ label, value }: MetricDetail) => {
|
||||||
|
const theme = useTheme();
|
||||||
|
return (
|
||||||
|
<Stack
|
||||||
|
direction="row"
|
||||||
|
justifyContent="space-between"
|
||||||
|
>
|
||||||
|
<Typography
|
||||||
|
variant="body2"
|
||||||
|
color={theme.palette.text.secondary}
|
||||||
|
>
|
||||||
|
{label}
|
||||||
|
</Typography>
|
||||||
|
<Typography variant="body2">{value}</Typography>
|
||||||
|
</Stack>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
interface MetricItemProps {
|
||||||
|
label: string;
|
||||||
|
progress: number;
|
||||||
|
details?: MetricDetail[];
|
||||||
|
}
|
||||||
|
|
||||||
|
const MetricItem = ({ label, progress, details }: MetricItemProps) => {
|
||||||
|
const theme = useTheme();
|
||||||
|
const isSmall = useMediaQuery(theme.breakpoints.down("md"));
|
||||||
|
return (
|
||||||
|
<Grid
|
||||||
|
size={isSmall ? 12 : 4}
|
||||||
|
sx={{
|
||||||
|
display: "flex",
|
||||||
|
flexDirection: "column",
|
||||||
|
alignItems: "center",
|
||||||
|
textAlign: "center",
|
||||||
|
gap: theme.spacing(SPACING.LG),
|
||||||
|
padding: theme.spacing(LAYOUT.XS),
|
||||||
|
borderRight: isSmall ? "none" : `1px solid ${theme.palette.divider}`,
|
||||||
|
borderBottom: isSmall ? `1px solid ${theme.palette.divider}` : "none",
|
||||||
|
"&:last-child": {
|
||||||
|
borderRight: "none",
|
||||||
|
borderBottom: "none",
|
||||||
|
paddingBottom: theme.spacing(SPACING.LG),
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Box
|
||||||
|
display="flex"
|
||||||
|
flexDirection="column"
|
||||||
|
alignItems="center"
|
||||||
|
>
|
||||||
|
<Gauge
|
||||||
|
progress={progress}
|
||||||
|
radius={GAUGE_RADIUS}
|
||||||
|
strokeWidth={GAUGE_STROKE_WIDTH}
|
||||||
|
/>
|
||||||
|
<Typography variant="body2">{label}</Typography>
|
||||||
|
</Box>
|
||||||
|
{details && details.length > 0 && (
|
||||||
|
<Box
|
||||||
|
width="100%"
|
||||||
|
paddingX={theme.spacing(LAYOUT.LG)}
|
||||||
|
>
|
||||||
|
{details.map((detail) => (
|
||||||
|
<MetricDetailRow
|
||||||
|
key={detail.label}
|
||||||
|
label={detail.label}
|
||||||
|
value={detail.value}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
</Grid>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
type LatestCheck = NonNullable<Monitor["recentChecks"]>[number];
|
||||||
|
|
||||||
|
const buildCpuMetric = (
|
||||||
|
check: LatestCheck,
|
||||||
|
t: (key: string) => string
|
||||||
|
): MetricConfig | null => {
|
||||||
|
if (!check.cpu || typeof check.cpu.usage_percent !== "number") {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const usagePercent = (check.cpu.usage_percent ?? 0) * PERCENTAGE_MULTIPLIER;
|
||||||
|
return {
|
||||||
|
key: "cpu",
|
||||||
|
label: t("pages.statusPages.monitorsList.infrastructure.cpu"),
|
||||||
|
hasData: true,
|
||||||
|
progress: usagePercent,
|
||||||
|
details: [
|
||||||
|
{
|
||||||
|
label: t("pages.statusPages.monitorsList.infrastructure.usage"),
|
||||||
|
value: `${usagePercent.toFixed(2)}%`,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const buildMemoryMetric = (
|
||||||
|
check: LatestCheck,
|
||||||
|
t: (key: string) => string
|
||||||
|
): MetricConfig | null => {
|
||||||
|
if (
|
||||||
|
!check.memory ||
|
||||||
|
typeof check.memory.usage_percent !== "number" ||
|
||||||
|
typeof check.memory.used_bytes !== "number" ||
|
||||||
|
typeof check.memory.total_bytes !== "number"
|
||||||
|
) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
key: "memory",
|
||||||
|
label: t("pages.statusPages.monitorsList.infrastructure.memory"),
|
||||||
|
hasData: true,
|
||||||
|
progress: (check.memory.usage_percent ?? 0) * PERCENTAGE_MULTIPLIER,
|
||||||
|
details: [
|
||||||
|
{
|
||||||
|
label: t("pages.statusPages.monitorsList.infrastructure.used"),
|
||||||
|
value: prettyBytes(check.memory.used_bytes ?? 0),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: t("pages.statusPages.monitorsList.infrastructure.total"),
|
||||||
|
value: prettyBytes(check.memory.total_bytes ?? 0),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const buildDiskMetric = (
|
||||||
|
check: LatestCheck,
|
||||||
|
t: (key: string) => string
|
||||||
|
): MetricConfig | null => {
|
||||||
|
if (!check.disk || check.disk.length === 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const disks = check.disk;
|
||||||
|
const avgUsagePercent =
|
||||||
|
(disks.reduce((acc, disk) => acc + (disk?.usage_percent ?? 0), 0) / disks.length) *
|
||||||
|
PERCENTAGE_MULTIPLIER;
|
||||||
|
const totalUsedBytes = disks.reduce((acc, disk) => acc + (disk?.used_bytes ?? 0), 0);
|
||||||
|
const totalTotalBytes = disks.reduce((acc, disk) => acc + (disk?.total_bytes ?? 0), 0);
|
||||||
|
|
||||||
|
return {
|
||||||
|
key: "disk",
|
||||||
|
label: t("pages.statusPages.monitorsList.infrastructure.disk"),
|
||||||
|
hasData: true,
|
||||||
|
progress: avgUsagePercent,
|
||||||
|
details: [
|
||||||
|
{
|
||||||
|
label: t("pages.statusPages.monitorsList.infrastructure.used"),
|
||||||
|
value: prettyBytes(totalUsedBytes),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: t("pages.statusPages.monitorsList.infrastructure.total"),
|
||||||
|
value: prettyBytes(totalTotalBytes),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
export const InfrastructureMetrics = ({ monitor }: { monitor: StatusPageMonitor }) => {
|
||||||
|
const theme = useTheme();
|
||||||
|
const { t } = useTranslation();
|
||||||
|
|
||||||
|
const latestCheck = monitor.recentChecks?.[0] ?? monitor.checks?.[0];
|
||||||
|
|
||||||
|
if (!latestCheck) {
|
||||||
|
return (
|
||||||
|
<Typography
|
||||||
|
variant="body2"
|
||||||
|
color={theme.palette.text.secondary}
|
||||||
|
>
|
||||||
|
{t("pages.statusPages.monitorsList.noData")}
|
||||||
|
</Typography>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const metrics: MetricConfig[] = [
|
||||||
|
buildCpuMetric(latestCheck, t),
|
||||||
|
buildMemoryMetric(latestCheck, t),
|
||||||
|
buildDiskMetric(latestCheck, t),
|
||||||
|
].filter((m): m is MetricConfig => m !== null);
|
||||||
|
|
||||||
|
if (metrics.length === 0) {
|
||||||
|
return (
|
||||||
|
<Typography
|
||||||
|
variant="body2"
|
||||||
|
color={theme.palette.text.secondary}
|
||||||
|
>
|
||||||
|
{t("pages.statusPages.monitorsList.noData")}
|
||||||
|
</Typography>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Grid
|
||||||
|
container
|
||||||
|
alignItems="center"
|
||||||
|
padding={theme.spacing(LAYOUT.XS)}
|
||||||
|
>
|
||||||
|
{metrics.map(({ key, label, progress, details }) => (
|
||||||
|
<MetricItem
|
||||||
|
key={key}
|
||||||
|
label={label}
|
||||||
|
progress={progress}
|
||||||
|
details={details}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</Grid>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -5,13 +5,15 @@ import Typography from "@mui/material/Typography";
|
|||||||
import { HistogramResponseTime, HeatmapResponseTime } from "@/Components/common";
|
import { HistogramResponseTime, HeatmapResponseTime } from "@/Components/common";
|
||||||
import { StatusLabel, BaseBox } from "@/Components/design-elements";
|
import { StatusLabel, BaseBox } from "@/Components/design-elements";
|
||||||
import { SwitchComponent } from "@/Components/inputs";
|
import { SwitchComponent } from "@/Components/inputs";
|
||||||
|
import { InfrastructureMetrics } from "@/Pages/StatusPage/Status/Components/InfrastructureMetrics";
|
||||||
|
|
||||||
import { useTheme } from "@mui/material/styles";
|
import { useTheme, type Theme } from "@mui/material/styles";
|
||||||
import { useSelector } from "react-redux";
|
import { useSelector } from "react-redux";
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import type { Monitor } from "@/Types/Monitor";
|
import type { Monitor } from "@/Types/Monitor";
|
||||||
import type { StatusPage } from "@/Types/StatusPage";
|
import type { StatusPage } from "@/Types/StatusPage";
|
||||||
import type { RootState } from "@/Types/state";
|
import type { RootState } from "@/Types/state";
|
||||||
|
import { LAYOUT, SPACING } from "@/Utils/Theme/constants";
|
||||||
|
|
||||||
interface StatusPageMonitor extends Monitor {
|
interface StatusPageMonitor extends Monitor {
|
||||||
checks?: Monitor["recentChecks"];
|
checks?: Monitor["recentChecks"];
|
||||||
@@ -22,6 +24,87 @@ interface MonitorsListProps {
|
|||||||
monitors: StatusPageMonitor[];
|
monitors: StatusPageMonitor[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const getMonitorBadgeStyles = (monitorType: string, theme: Theme) => {
|
||||||
|
// for future: specific badge styles can be defined here based on monitor type
|
||||||
|
const badgeConfig: Record<string, { color: string; bg: string }> = {
|
||||||
|
hardware: {
|
||||||
|
color: theme.palette.background.paper,
|
||||||
|
bg: theme.palette.info.light,
|
||||||
|
},
|
||||||
|
http: {
|
||||||
|
color: theme.palette.background.paper,
|
||||||
|
bg: theme.palette.success.light,
|
||||||
|
},
|
||||||
|
ping: {
|
||||||
|
color: theme.palette.background.paper,
|
||||||
|
bg: theme.palette.success.light,
|
||||||
|
},
|
||||||
|
port: {
|
||||||
|
color: theme.palette.background.paper,
|
||||||
|
bg: theme.palette.success.light,
|
||||||
|
},
|
||||||
|
docker: {
|
||||||
|
color: theme.palette.background.paper,
|
||||||
|
bg: theme.palette.success.light,
|
||||||
|
},
|
||||||
|
pagespeed: {
|
||||||
|
color: theme.palette.background.paper,
|
||||||
|
bg: theme.palette.success.light,
|
||||||
|
},
|
||||||
|
game: {
|
||||||
|
color: theme.palette.background.paper,
|
||||||
|
bg: theme.palette.success.light,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const config = badgeConfig[monitorType] ?? badgeConfig.http;
|
||||||
|
return {
|
||||||
|
backgroundColor: config.bg,
|
||||||
|
color: config.color,
|
||||||
|
padding: `${theme.spacing(SPACING.SM)} ${theme.spacing(SPACING.LG)}`,
|
||||||
|
borderRadius: theme.shape.borderRadius,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
// Extracted component for monitor content below the header row
|
||||||
|
const MonitorContent = ({
|
||||||
|
monitor,
|
||||||
|
statusPage,
|
||||||
|
chartType,
|
||||||
|
}: {
|
||||||
|
monitor: Monitor & { checks?: Monitor["recentChecks"] };
|
||||||
|
statusPage: StatusPage;
|
||||||
|
chartType: string;
|
||||||
|
}) => {
|
||||||
|
const theme = useTheme();
|
||||||
|
const isInfrastructureMonitor = monitor?.type === "hardware";
|
||||||
|
|
||||||
|
if (isInfrastructureMonitor) {
|
||||||
|
if (statusPage.showInfrastructure === false) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return <InfrastructureMetrics monitor={monitor} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (statusPage.showCharts === false) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box sx={{ overflow: "hidden", minWidth: 0, flex: 1, mb: theme.spacing(SPACING.LG) }}>
|
||||||
|
{chartType === "histogram" ? (
|
||||||
|
<HistogramResponseTime
|
||||||
|
height={{ xs: 50, md: 100 }}
|
||||||
|
gap={{ xs: theme.spacing(SPACING.SM), md: theme.spacing(LAYOUT.SM) }}
|
||||||
|
checks={monitor?.checks?.slice().reverse() ?? []}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<HeatmapResponseTime checks={monitor?.checks?.slice().reverse() ?? []} />
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
export const MonitorsList = ({ statusPage, monitors }: MonitorsListProps) => {
|
export const MonitorsList = ({ statusPage, monitors }: MonitorsListProps) => {
|
||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
@@ -31,11 +114,12 @@ export const MonitorsList = ({ statusPage, monitors }: MonitorsListProps) => {
|
|||||||
const [chartType, setChartType] = useState<"histogram" | "heatmap">("histogram");
|
const [chartType, setChartType] = useState<"histogram" | "heatmap">("histogram");
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Stack gap={theme.spacing(8)}>
|
<Stack gap={theme.spacing(LAYOUT.MD)}>
|
||||||
{statusPage.showCharts !== false && (
|
{statusPage.showCharts && (
|
||||||
<Stack
|
<Stack
|
||||||
direction={"row"}
|
direction={"row"}
|
||||||
alignItems={"center"}
|
alignItems={"center"}
|
||||||
|
gap={theme.spacing(LAYOUT.SM)}
|
||||||
>
|
>
|
||||||
<Typography>{t("pages.statusPages.monitorsList.chartTypeHeatmap")}</Typography>
|
<Typography>{t("pages.statusPages.monitorsList.chartTypeHeatmap")}</Typography>
|
||||||
<SwitchComponent
|
<SwitchComponent
|
||||||
@@ -56,52 +140,62 @@ export const MonitorsList = ({ statusPage, monitors }: MonitorsListProps) => {
|
|||||||
return (
|
return (
|
||||||
<BaseBox
|
<BaseBox
|
||||||
key={monitor.id}
|
key={monitor.id}
|
||||||
padding={theme.spacing(4)}
|
padding={theme.spacing(LAYOUT.MD)}
|
||||||
>
|
>
|
||||||
<Stack
|
<Stack
|
||||||
direction="row"
|
direction="row"
|
||||||
alignItems="center"
|
alignItems="center"
|
||||||
justifyContent="space-between"
|
justifyContent="space-between"
|
||||||
gap={theme.spacing(4)}
|
gap={theme.spacing(LAYOUT.XS)}
|
||||||
mb={statusPage.showCharts !== false ? theme.spacing(4) : 0}
|
mb={theme.spacing(LAYOUT.XS)}
|
||||||
>
|
>
|
||||||
<Box sx={{ overflow: "hidden", minWidth: 0, flex: 1 }}>
|
<Box sx={{ overflow: "hidden", minWidth: 0, flex: 1 }}>
|
||||||
<Typography
|
<Stack
|
||||||
variant="h6"
|
direction="row"
|
||||||
sx={{
|
alignItems="center"
|
||||||
overflow: "hidden",
|
gap={theme.spacing(SPACING.LG)}
|
||||||
textOverflow: "ellipsis",
|
mb={theme.spacing(SPACING.SM)}
|
||||||
whiteSpace: "nowrap",
|
|
||||||
}}
|
|
||||||
>
|
>
|
||||||
{monitor.name}
|
<Typography
|
||||||
</Typography>
|
variant="h6"
|
||||||
{showURL && (
|
sx={{
|
||||||
|
overflow: "hidden",
|
||||||
|
textOverflow: "ellipsis",
|
||||||
|
whiteSpace: "nowrap",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{monitor.name}
|
||||||
|
</Typography>
|
||||||
|
<Typography
|
||||||
|
variant="caption"
|
||||||
|
sx={getMonitorBadgeStyles(monitor?.type ?? "", theme)}
|
||||||
|
>
|
||||||
|
{t(
|
||||||
|
`pages.common.monitors.monitorTypes.option${monitor?.type.charAt(0).toUpperCase() + monitor?.type.slice(1)}`
|
||||||
|
)}
|
||||||
|
</Typography>
|
||||||
|
</Stack>
|
||||||
|
{showURL && monitor?.url && (
|
||||||
<Typography
|
<Typography
|
||||||
variant="body2"
|
variant="body2"
|
||||||
color="text.secondary"
|
color={theme.palette.text.secondary}
|
||||||
|
sx={{
|
||||||
|
overflow: "hidden",
|
||||||
|
textOverflow: "ellipsis",
|
||||||
|
whiteSpace: "nowrap",
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
{monitor.url}
|
{monitor.url}
|
||||||
</Typography>
|
</Typography>
|
||||||
)}
|
)}
|
||||||
</Box>
|
</Box>
|
||||||
<StatusLabel status={monitor.status} />
|
<StatusLabel status={monitor?.status} />
|
||||||
</Stack>
|
</Stack>
|
||||||
{statusPage.showCharts !== false && (
|
<MonitorContent
|
||||||
<Box sx={{ overflow: "hidden", minWidth: 0, flex: 1 }}>
|
monitor={monitor}
|
||||||
{chartType === "histogram" ? (
|
statusPage={statusPage}
|
||||||
<HistogramResponseTime
|
chartType={chartType}
|
||||||
height={{ xs: 50, md: 100 }}
|
/>
|
||||||
gap={{ xs: theme.spacing(0.5), md: theme.spacing(5) }}
|
|
||||||
checks={monitor?.checks?.slice().reverse() ?? []}
|
|
||||||
/>
|
|
||||||
) : (
|
|
||||||
<HeatmapResponseTime
|
|
||||||
checks={monitor?.checks?.slice().reverse() ?? []}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</Box>
|
|
||||||
)}
|
|
||||||
</BaseBox>
|
</BaseBox>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
|
|||||||
@@ -23,16 +23,17 @@ const StatusPageView = () => {
|
|||||||
const isSmall = useMediaQuery(theme.breakpoints.down("md"));
|
const isSmall = useMediaQuery(theme.breakpoints.down("md"));
|
||||||
const isPublic = location.pathname.startsWith("/status/public");
|
const isPublic = location.pathname.startsWith("/status/public");
|
||||||
|
|
||||||
const apiUrl = url ? `/status-page/${url}?type=uptime` : null;
|
const apiUrl = url ? `/status-page/${url}?type=uptime&type=infrastructure` : null;
|
||||||
|
|
||||||
const { data, isLoading, error } = useGet<StatusPageResponse>(apiUrl);
|
const { data, isLoading, error } = useGet<StatusPageResponse>(apiUrl);
|
||||||
|
|
||||||
const statusPage = data?.statusPage;
|
const statusPage = data?.statusPage;
|
||||||
const monitors = data?.monitors ?? [];
|
const monitors = data?.monitors ?? [];
|
||||||
|
const infrastructureMonitors = data?.infrastructureMonitors ?? [];
|
||||||
|
|
||||||
if (!statusPage) return null;
|
if (!statusPage) return null;
|
||||||
|
|
||||||
if (monitors?.length === 0) {
|
if (monitors?.length === 0 && infrastructureMonitors?.length === 0) {
|
||||||
return (
|
return (
|
||||||
<BasePage
|
<BasePage
|
||||||
loading={isLoading}
|
loading={isLoading}
|
||||||
|
|||||||
@@ -97,7 +97,7 @@ export const StatusPagesTable = ({
|
|||||||
{
|
{
|
||||||
id: "type",
|
id: "type",
|
||||||
content: t("common.table.headers.type"),
|
content: t("common.table.headers.type"),
|
||||||
render: (row) => row.type,
|
render: (row) => row.type.join(", "),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: "status",
|
id: "status",
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
export const CHECK_TTL_SENTINEL = 366;
|
||||||
|
|
||||||
export interface CheckMetadata {
|
export interface CheckMetadata {
|
||||||
monitorId: string;
|
monitorId: string;
|
||||||
teamId: string;
|
teamId: string;
|
||||||
@@ -125,9 +127,6 @@ export interface Check {
|
|||||||
timings?: CheckTimings;
|
timings?: CheckTimings;
|
||||||
statusCode: number;
|
statusCode: number;
|
||||||
message: string;
|
message: string;
|
||||||
ack: boolean;
|
|
||||||
ackAt?: string | null;
|
|
||||||
expiry: string;
|
|
||||||
cpu?: CheckCpuInfo;
|
cpu?: CheckCpuInfo;
|
||||||
memory?: CheckMemoryInfo;
|
memory?: CheckMemoryInfo;
|
||||||
disk?: CheckDiskInfo[];
|
disk?: CheckDiskInfo[];
|
||||||
@@ -140,7 +139,6 @@ export interface Check {
|
|||||||
seo?: number;
|
seo?: number;
|
||||||
performance?: number;
|
performance?: number;
|
||||||
audits?: CheckAudits;
|
audits?: CheckAudits;
|
||||||
__v: number;
|
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
updatedAt: string;
|
updatedAt: string;
|
||||||
}
|
}
|
||||||
@@ -243,10 +241,7 @@ export interface ChecksSummary {
|
|||||||
downChecks: number;
|
downChecks: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type CheckSnapshot = Omit<
|
export type CheckSnapshot = Omit<Check, "metadata" | "__v" | "updatedAt"> & {
|
||||||
Check,
|
|
||||||
"metadata" | "ack" | "ackAt" | "expiry" | "__v" | "updatedAt"
|
|
||||||
> & {
|
|
||||||
originalResponseTime: number;
|
originalResponseTime: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ export const NotificationChannels = [
|
|||||||
"webhook",
|
"webhook",
|
||||||
"pager_duty",
|
"pager_duty",
|
||||||
"matrix",
|
"matrix",
|
||||||
|
"teams",
|
||||||
] as const;
|
] as const;
|
||||||
export type NotificationChannel = (typeof NotificationChannels)[number];
|
export type NotificationChannel = (typeof NotificationChannels)[number];
|
||||||
|
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
import type { Monitor } from "@/Types/Monitor";
|
import type { Monitor } from "@/Types/Monitor";
|
||||||
|
export type MonitorDisplayType = "uptime" | "infrastructure";
|
||||||
|
|
||||||
export interface StatusPage {
|
export interface StatusPage {
|
||||||
id: string;
|
id: string;
|
||||||
userId: string;
|
userId: string;
|
||||||
teamId: string;
|
teamId: string;
|
||||||
type: string;
|
type: MonitorDisplayType[];
|
||||||
companyName: string;
|
companyName: string;
|
||||||
url: string;
|
url: string;
|
||||||
timezone?: string;
|
timezone?: string;
|
||||||
@@ -20,6 +21,7 @@ export interface StatusPage {
|
|||||||
showCharts: boolean;
|
showCharts: boolean;
|
||||||
showUptimePercentage: boolean;
|
showUptimePercentage: boolean;
|
||||||
showAdminLoginLink: boolean;
|
showAdminLoginLink: boolean;
|
||||||
|
showInfrastructure: boolean;
|
||||||
customCSS: string;
|
customCSS: string;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
updatedAt: string;
|
updatedAt: string;
|
||||||
@@ -28,4 +30,5 @@ export interface StatusPage {
|
|||||||
export interface StatusPageResponse {
|
export interface StatusPageResponse {
|
||||||
statusPage: StatusPage;
|
statusPage: StatusPage;
|
||||||
monitors: Monitor[];
|
monitors: Monitor[];
|
||||||
|
infrastructureMonitors?: Monitor[];
|
||||||
}
|
}
|
||||||
@@ -45,6 +45,11 @@ const matrixSchema = baseSchema.extend({
|
|||||||
accessToken: z.string().min(1, "Access token is required"),
|
accessToken: z.string().min(1, "Access token is required"),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const teamsSchema = baseSchema.extend({
|
||||||
|
type: z.literal("teams"),
|
||||||
|
address: z.string().min(1, "Webhook URL is required").url("Please enter a valid URL"),
|
||||||
|
});
|
||||||
|
|
||||||
export const notificationSchema = z.discriminatedUnion("type", [
|
export const notificationSchema = z.discriminatedUnion("type", [
|
||||||
emailSchema,
|
emailSchema,
|
||||||
slackSchema,
|
slackSchema,
|
||||||
@@ -52,6 +57,7 @@ export const notificationSchema = z.discriminatedUnion("type", [
|
|||||||
webhookSchema,
|
webhookSchema,
|
||||||
pagerDutySchema,
|
pagerDutySchema,
|
||||||
matrixSchema,
|
matrixSchema,
|
||||||
|
teamsSchema,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
export type NotificationFormData = z.infer<typeof notificationSchema>;
|
export type NotificationFormData = z.infer<typeof notificationSchema>;
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { CHECK_TTL_SENTINEL } from "@/Types/Check";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
|
|
||||||
export const settingsSchema = z.object({
|
export const settingsSchema = z.object({
|
||||||
@@ -11,7 +12,11 @@ export const settingsSchema = z.object({
|
|||||||
systemEmailSecure: z.boolean().optional(),
|
systemEmailSecure: z.boolean().optional(),
|
||||||
systemEmailPool: z.boolean().optional(),
|
systemEmailPool: z.boolean().optional(),
|
||||||
showURL: z.boolean().optional(),
|
showURL: z.boolean().optional(),
|
||||||
checkTTL: z.number().int().min(1, "Please enter a value").max(365, "Maximum 365 days"),
|
checkTTL: z
|
||||||
|
.number()
|
||||||
|
.int()
|
||||||
|
.min(1, "Please enter a value")
|
||||||
|
.max(CHECK_TTL_SENTINEL, `Maximum ${CHECK_TTL_SENTINEL}`),
|
||||||
pagespeedApiKey: z
|
pagespeedApiKey: z
|
||||||
.string()
|
.string()
|
||||||
.transform((val) => (val.trim() === "" ? undefined : val.trim()))
|
.transform((val) => (val.trim() === "" ? undefined : val.trim()))
|
||||||
|
|||||||
@@ -14,12 +14,16 @@ export const statusPageSchema = z.object({
|
|||||||
"URL can only contain lowercase letters, numbers, and hyphens"
|
"URL can only contain lowercase letters, numbers, and hyphens"
|
||||||
),
|
),
|
||||||
timezone: z.string().optional(),
|
timezone: z.string().optional(),
|
||||||
|
type: z
|
||||||
|
.array(z.enum(["uptime", "infrastructure"]))
|
||||||
|
.min(1, "At least one type is required"),
|
||||||
color: z.string().min(1, "Color is required"),
|
color: z.string().min(1, "Color is required"),
|
||||||
monitors: z.array(z.string()).min(1, "At least one monitor is required"),
|
monitors: z.array(z.string()).min(1, "At least one monitor is required"),
|
||||||
isPublished: z.boolean(),
|
isPublished: z.boolean(),
|
||||||
showCharts: z.boolean(),
|
showCharts: z.boolean(),
|
||||||
showUptimePercentage: z.boolean(),
|
showUptimePercentage: z.boolean(),
|
||||||
showAdminLoginLink: z.boolean(),
|
showAdminLoginLink: z.boolean(),
|
||||||
|
showInfrastructure: z.boolean(),
|
||||||
customCSS: z.string().optional(),
|
customCSS: z.string().optional(),
|
||||||
logo: z
|
logo: z
|
||||||
.object({
|
.object({
|
||||||
|
|||||||
@@ -288,7 +288,13 @@ const logoImageValidation = joi
|
|||||||
.optional(); // Make entire object optional
|
.optional(); // Make entire object optional
|
||||||
|
|
||||||
const statusPageValidation = joi.object({
|
const statusPageValidation = joi.object({
|
||||||
type: joi.string().valid("uptime").required(),
|
type: joi
|
||||||
|
.alternatives()
|
||||||
|
.try(
|
||||||
|
joi.string().valid("uptime", "infrastructure"),
|
||||||
|
joi.array().items(joi.string().valid("uptime", "infrastructure"))
|
||||||
|
)
|
||||||
|
.required(),
|
||||||
isPublished: joi.bool(),
|
isPublished: joi.bool(),
|
||||||
companyName: joi
|
companyName: joi
|
||||||
.string()
|
.string()
|
||||||
@@ -317,6 +323,7 @@ const statusPageValidation = joi.object({
|
|||||||
showUptimePercentage: joi.boolean(),
|
showUptimePercentage: joi.boolean(),
|
||||||
showCharts: joi.boolean(),
|
showCharts: joi.boolean(),
|
||||||
showAdminLoginLink: joi.boolean(),
|
showAdminLoginLink: joi.boolean(),
|
||||||
|
showInfrastructure: joi.boolean(),
|
||||||
});
|
});
|
||||||
|
|
||||||
const settingsValidation = joi.object({
|
const settingsValidation = joi.object({
|
||||||
|
|||||||
@@ -407,6 +407,17 @@
|
|||||||
"paused": "paused",
|
"paused": "paused",
|
||||||
"total": "total",
|
"total": "total",
|
||||||
"up": "up"
|
"up": "up"
|
||||||
|
},
|
||||||
|
"monitorTypes": {
|
||||||
|
"optionDocker": "Docker",
|
||||||
|
"optionGame": "Game",
|
||||||
|
"optionHttp": "HTTP(S)",
|
||||||
|
"optionPing": "Ping",
|
||||||
|
"optionPort": "Port",
|
||||||
|
"optionPagespeed": "PageSpeed",
|
||||||
|
"optionHardware": "Infrastructure",
|
||||||
|
"optionGrpc": "gRPC",
|
||||||
|
"optionWebSocket": "WebSocket"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -534,19 +545,12 @@
|
|||||||
},
|
},
|
||||||
"type": {
|
"type": {
|
||||||
"description": "Select the type of check to perform",
|
"description": "Select the type of check to perform",
|
||||||
"optionDocker": "Docker",
|
|
||||||
"optionDockerDescription": "Use Docker to monitor if a container is running.",
|
"optionDockerDescription": "Use Docker to monitor if a container is running.",
|
||||||
"optionGame": "Game",
|
|
||||||
"optionGameDescription": "Monitor if a specific game server is online.",
|
"optionGameDescription": "Monitor if a specific game server is online.",
|
||||||
"optionGrpc": "gRPC",
|
|
||||||
"optionGrpcDescription": "Monitor gRPC services using the standard Health Checking Protocol.",
|
"optionGrpcDescription": "Monitor gRPC services using the standard Health Checking Protocol.",
|
||||||
"optionWebSocket": "WebSocket",
|
|
||||||
"optionWebSocketDescription": "Monitor WebSocket endpoints for connection health and response time.",
|
"optionWebSocketDescription": "Monitor WebSocket endpoints for connection health and response time.",
|
||||||
"optionHttp": "HTTP(S)",
|
|
||||||
"optionHttpDescription": "Use HTTP(S) to monitor your website or API endpoint.",
|
"optionHttpDescription": "Use HTTP(S) to monitor your website or API endpoint.",
|
||||||
"optionPing": "Ping",
|
|
||||||
"optionPingDescription": "Use ICMP Ping to monitor if a server is online.",
|
"optionPingDescription": "Use ICMP Ping to monitor if a server is online.",
|
||||||
"optionPort": "Port",
|
|
||||||
"optionPortDescription": "Monitor if a specific port on a server is open.",
|
"optionPortDescription": "Monitor if a specific port on a server is open.",
|
||||||
"title": "Type"
|
"title": "Type"
|
||||||
},
|
},
|
||||||
@@ -1041,7 +1045,7 @@
|
|||||||
},
|
},
|
||||||
"stats": {
|
"stats": {
|
||||||
"title": "Monitor history",
|
"title": "Monitor history",
|
||||||
"description": "Define how long you want to retain historical data. You can also clear all existing data.",
|
"description": "Clear all monitoring history and statistics for your team. This action is irreversible.",
|
||||||
"option": {
|
"option": {
|
||||||
"clear": {
|
"clear": {
|
||||||
"label": "Clear all stats. This is irreversible."
|
"label": "Clear all stats. This is irreversible."
|
||||||
@@ -1052,6 +1056,16 @@
|
|||||||
"description": "This cannot be undone"
|
"description": "This cannot be undone"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"retention": {
|
||||||
|
"title": "Check retention",
|
||||||
|
"description": "Set how long check data is retained before being automatically cleaned up.",
|
||||||
|
"option": {
|
||||||
|
"days": {
|
||||||
|
"label": "Retention period (days)",
|
||||||
|
"unlimited": "Unlimited"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
"thresholds": {
|
"thresholds": {
|
||||||
"title": "Global Thresholds",
|
"title": "Global Thresholds",
|
||||||
"description": "Set global CPU, Memory, Disk, and Temperature thresholds for infrastructure monitoring. These apply to all hardware monitors unless overridden.",
|
"description": "Set global CPU, Memory, Disk, and Temperature thresholds for infrastructure monitoring. These apply to all hardware monitors unless overridden.",
|
||||||
@@ -1168,7 +1182,22 @@
|
|||||||
},
|
},
|
||||||
"monitorsList": {
|
"monitorsList": {
|
||||||
"chartTypeHeatmap": "Heatmap",
|
"chartTypeHeatmap": "Heatmap",
|
||||||
"chartTypeHistogram": "Histogram"
|
"chartTypeHistogram": "Histogram",
|
||||||
|
"noData": "No data available",
|
||||||
|
"infrastructure": {
|
||||||
|
"title": "Infrastructure",
|
||||||
|
"cpu": "CPU",
|
||||||
|
"memory": "RAM",
|
||||||
|
"memoryText": "Memory",
|
||||||
|
"disk": "Disk",
|
||||||
|
"usage": "Usage",
|
||||||
|
"used": "Used",
|
||||||
|
"total": "Total"
|
||||||
|
},
|
||||||
|
"uptime": {
|
||||||
|
"title": "Uptime",
|
||||||
|
"responseTime": "Response time"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"statusBar": {
|
"statusBar": {
|
||||||
"allDown": "All systems are down",
|
"allDown": "All systems are down",
|
||||||
@@ -1260,6 +1289,9 @@
|
|||||||
},
|
},
|
||||||
"showAdminLoginLink": {
|
"showAdminLoginLink": {
|
||||||
"label": "Show admin login link"
|
"label": "Show admin login link"
|
||||||
|
},
|
||||||
|
"showInfrastructure": {
|
||||||
|
"label": "Show infrastructure metrics"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ import {
|
|||||||
DiscordProvider,
|
DiscordProvider,
|
||||||
PagerDutyProvider,
|
PagerDutyProvider,
|
||||||
MatrixProvider,
|
MatrixProvider,
|
||||||
|
TeamsProvider,
|
||||||
// Interfaces
|
// Interfaces
|
||||||
INetworkService,
|
INetworkService,
|
||||||
IEmailService,
|
IEmailService,
|
||||||
@@ -228,6 +229,7 @@ export const initializeServices = async ({
|
|||||||
const discordProvider = new DiscordProvider(logger);
|
const discordProvider = new DiscordProvider(logger);
|
||||||
const pagerDutyProvider = new PagerDutyProvider(logger);
|
const pagerDutyProvider = new PagerDutyProvider(logger);
|
||||||
const matrixProvider = new MatrixProvider(logger);
|
const matrixProvider = new MatrixProvider(logger);
|
||||||
|
const teamsProvider = new TeamsProvider(logger);
|
||||||
|
|
||||||
const notificationsService = new NotificationsService(
|
const notificationsService = new NotificationsService(
|
||||||
notificationsRepository,
|
notificationsRepository,
|
||||||
@@ -238,6 +240,7 @@ export const initializeServices = async ({
|
|||||||
discordProvider,
|
discordProvider,
|
||||||
pagerDutyProvider,
|
pagerDutyProvider,
|
||||||
matrixProvider,
|
matrixProvider,
|
||||||
|
teamsProvider,
|
||||||
settingsService,
|
settingsService,
|
||||||
logger,
|
logger,
|
||||||
notificationMessageBuilder
|
notificationMessageBuilder
|
||||||
@@ -249,6 +252,7 @@ export const initializeServices = async ({
|
|||||||
statusService,
|
statusService,
|
||||||
notificationsService,
|
notificationsService,
|
||||||
checkService,
|
checkService,
|
||||||
|
settingsService,
|
||||||
bufferService,
|
bufferService,
|
||||||
incidentService,
|
incidentService,
|
||||||
maintenanceWindowsRepository,
|
maintenanceWindowsRepository,
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
import { Request, Response, NextFunction } from "express";
|
import { Request, Response, NextFunction } from "express";
|
||||||
import { AppError } from "@/utils/AppError.js";
|
import { AppError } from "@/utils/AppError.js";
|
||||||
import { requireTeamId, requireUserRoles } from "./controllerUtils.js";
|
import { requireTeamId, requireUserEmail, requireUserId, requireUserRoles } from "@/controllers/controllerUtils.js";
|
||||||
import type { UserRole } from "@/types/user.js";
|
|
||||||
|
|
||||||
import {
|
import {
|
||||||
registrationBodyValidation,
|
registrationBodyValidation,
|
||||||
@@ -20,15 +19,16 @@ import {
|
|||||||
editSuperadminUserByIdBodyValidation,
|
editSuperadminUserByIdBodyValidation,
|
||||||
editUserPasswordByIdBodyValidation,
|
editUserPasswordByIdBodyValidation,
|
||||||
} from "@/validation/userValidation.js";
|
} from "@/validation/userValidation.js";
|
||||||
|
import { IUserService } from "@/service/index.js";
|
||||||
|
|
||||||
const SERVICE_NAME = "authController";
|
const SERVICE_NAME = "authController";
|
||||||
|
|
||||||
class AuthController {
|
class AuthController {
|
||||||
static SERVICE_NAME = SERVICE_NAME;
|
static SERVICE_NAME = SERVICE_NAME;
|
||||||
|
|
||||||
private userService: any;
|
private userService: IUserService;
|
||||||
|
|
||||||
constructor(userService: any) {
|
constructor(userService: IUserService) {
|
||||||
this.userService = userService;
|
this.userService = userService;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -41,11 +41,12 @@ class AuthController {
|
|||||||
const newUser = req.body.user;
|
const newUser = req.body.user;
|
||||||
const newUserToken = req.body.token;
|
const newUserToken = req.body.token;
|
||||||
if (newUser?.email) {
|
if (newUser?.email) {
|
||||||
newUser.email = newUser.email.toLowerCase();
|
const newUserEmail = requireUserEmail(newUser.email);
|
||||||
|
newUser.email = newUserEmail.toLowerCase();
|
||||||
}
|
}
|
||||||
registrationBodyValidation.parse(newUser);
|
const validatedBody = registrationBodyValidation.parse(newUser);
|
||||||
|
|
||||||
const { user, token } = await this.userService.registerUser(newUser, newUserToken, req.file);
|
const { user, token } = await this.userService.registerUser(validatedBody, newUserToken, req?.file ?? null);
|
||||||
res.status(200).json({
|
res.status(200).json({
|
||||||
success: true,
|
success: true,
|
||||||
msg: "User registered successfully",
|
msg: "User registered successfully",
|
||||||
@@ -62,11 +63,11 @@ class AuthController {
|
|||||||
if (userData?.email) {
|
if (userData?.email) {
|
||||||
userData.email = userData.email.toLowerCase();
|
userData.email = userData.email.toLowerCase();
|
||||||
}
|
}
|
||||||
createUserBodyValidation.parse(userData);
|
const validatedBody = createUserBodyValidation.parse(userData);
|
||||||
|
|
||||||
const teamId = requireTeamId(req.user?.teamId);
|
const teamId = requireTeamId(req.user?.teamId);
|
||||||
const actorRoles = requireUserRoles(req.user?.role) as UserRole[];
|
const actorRoles = requireUserRoles(req.user?.role);
|
||||||
const newUser = await this.userService.createUser(userData, teamId, actorRoles, req.file);
|
const newUser = await this.userService.createUser(validatedBody, teamId, actorRoles, req?.file ?? null);
|
||||||
res.status(201).json({
|
res.status(201).json({
|
||||||
success: true,
|
success: true,
|
||||||
msg: "User created successfully",
|
msg: "User created successfully",
|
||||||
@@ -100,8 +101,10 @@ class AuthController {
|
|||||||
|
|
||||||
editUser = async (req: Request, res: Response, next: NextFunction) => {
|
editUser = async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
editUserBodyValidation.parse(req.body);
|
const validatedBody = editUserBodyValidation.parse(req.body);
|
||||||
const updatedUser = await this.userService.editUser(req.body, req.file, req.user);
|
const userId = requireUserId(req.user?.id);
|
||||||
|
const userEmail = requireUserEmail(req.user?.email);
|
||||||
|
const updatedUser = await this.userService.editUser(validatedBody, req?.file ?? null, userId, userEmail);
|
||||||
|
|
||||||
res.status(200).json({
|
res.status(200).json({
|
||||||
success: true,
|
success: true,
|
||||||
@@ -170,7 +173,15 @@ class AuthController {
|
|||||||
|
|
||||||
deleteUser = async (req: Request, res: Response, next: NextFunction) => {
|
deleteUser = async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
await this.userService.deleteUser(req.user);
|
const userId = requireUserId(req.user?.id);
|
||||||
|
const teamId = requireTeamId(req.user?.teamId);
|
||||||
|
const roles = requireUserRoles(req.user?.role);
|
||||||
|
|
||||||
|
await this.userService.deleteUser({
|
||||||
|
userId,
|
||||||
|
teamId,
|
||||||
|
roles,
|
||||||
|
});
|
||||||
return res.status(200).json({
|
return res.status(200).json({
|
||||||
success: true,
|
success: true,
|
||||||
msg: "User deleted successfully",
|
msg: "User deleted successfully",
|
||||||
@@ -182,9 +193,12 @@ class AuthController {
|
|||||||
|
|
||||||
deleteUserById = async (req: Request, res: Response, next: NextFunction) => {
|
deleteUserById = async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
getUserByIdParamValidation.parse(req.params);
|
const validatedParams = getUserByIdParamValidation.parse(req.params);
|
||||||
const targetUserId = req.params.userId;
|
const targetUserId = validatedParams.userId;
|
||||||
await this.userService.deleteUserById(req.user, targetUserId);
|
const actorId = requireUserId(req.user?.id);
|
||||||
|
const actorTeamId = requireTeamId(req.user?.teamId);
|
||||||
|
const actorRoles = requireUserRoles(req.user?.role);
|
||||||
|
await this.userService.deleteUserById({ actorId, actorTeamId, actorRoles, targetUserId });
|
||||||
return res.status(200).json({
|
return res.status(200).json({
|
||||||
success: true,
|
success: true,
|
||||||
msg: "User removed successfully",
|
msg: "User removed successfully",
|
||||||
@@ -209,19 +223,9 @@ class AuthController {
|
|||||||
|
|
||||||
getUserById = async (req: Request, res: Response, next: NextFunction) => {
|
getUserById = async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
getUserByIdParamValidation.parse(req.params);
|
const validatedParams = getUserByIdParamValidation.parse(req.params);
|
||||||
const userId = req?.params?.userId;
|
const actorRoles = requireUserRoles(req.user?.role);
|
||||||
const roles = req?.user?.role;
|
const user = await this.userService.getUserById(actorRoles, validatedParams.userId);
|
||||||
|
|
||||||
if (!userId) {
|
|
||||||
throw new Error("No user ID in request");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!roles || roles.length === 0) {
|
|
||||||
throw new Error("No roles in request");
|
|
||||||
}
|
|
||||||
|
|
||||||
const user = await this.userService.getUserById(roles, userId);
|
|
||||||
|
|
||||||
return res.status(200).json({ success: true, msg: "ok", data: user });
|
return res.status(200).json({ success: true, msg: "ok", data: user });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -231,24 +235,19 @@ class AuthController {
|
|||||||
|
|
||||||
editUserById = async (req: Request, res: Response, next: NextFunction) => {
|
editUserById = async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
const roles = req?.user?.role;
|
const actorRoles = requireUserRoles(req.user?.role);
|
||||||
|
const actorId = requireUserId(req.user?.id);
|
||||||
|
|
||||||
if (!roles || !roles.includes("superadmin")) {
|
if (!actorRoles.includes("superadmin")) {
|
||||||
throw new AppError({ message: "Unauthorized", status: 403 });
|
throw new AppError({ message: "Unauthorized", status: 403 });
|
||||||
}
|
}
|
||||||
|
|
||||||
const userId = req.params.userId as string;
|
const validatedParams = editUserByIdParamValidation.parse(req.params);
|
||||||
const user = { ...req.body };
|
|
||||||
|
|
||||||
editUserByIdParamValidation.parse(req.params);
|
|
||||||
// If this is superadmin self edit, allow "superadmin" role
|
// If this is superadmin self edit, allow "superadmin" role
|
||||||
if (userId === req.user?.id) {
|
const validatedBody =
|
||||||
editSuperadminUserByIdBodyValidation.parse(req.body);
|
validatedParams.userId === actorId ? editSuperadminUserByIdBodyValidation.parse(req.body) : editUserByIdBodyValidation.parse(req.body);
|
||||||
} else {
|
|
||||||
editUserByIdBodyValidation.parse(req.body);
|
|
||||||
}
|
|
||||||
|
|
||||||
await this.userService.editUserById(userId, user);
|
await this.userService.editUserById(validatedParams.userId, validatedBody);
|
||||||
return res.status(200).json({ success: true, msg: "ok" });
|
return res.status(200).json({ success: true, msg: "ok" });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
next(error);
|
next(error);
|
||||||
@@ -257,16 +256,14 @@ class AuthController {
|
|||||||
|
|
||||||
editUserPasswordById = async (req: Request, res: Response, next: NextFunction) => {
|
editUserPasswordById = async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
const roles = req?.user?.role;
|
const actorRoles = requireUserRoles(req.user?.role);
|
||||||
if (!roles || !roles.includes("superadmin")) {
|
if (!actorRoles.includes("superadmin")) {
|
||||||
throw new AppError({ message: "Unauthorized", status: 403 });
|
throw new AppError({ message: "Unauthorized", status: 403 });
|
||||||
}
|
}
|
||||||
|
|
||||||
const userId = req.params.userId as string;
|
const validatedParams = editUserByIdParamValidation.parse(req.params);
|
||||||
editUserByIdParamValidation.parse(req.params);
|
const validatedBody = editUserPasswordByIdBodyValidation.parse(req.body);
|
||||||
editUserPasswordByIdBodyValidation.parse(req.body);
|
await this.userService.setPasswordByUserId(validatedParams.userId, validatedBody.password);
|
||||||
const updatedPassword = req.body.password;
|
|
||||||
await this.userService.setPasswordByUserId(userId, updatedPassword);
|
|
||||||
return res.status(200).json({ success: true, msg: "Password reset successfully" });
|
return res.status(200).json({ success: true, msg: "Password reset successfully" });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
next(error);
|
next(error);
|
||||||
|
|||||||
@@ -4,18 +4,19 @@ import {
|
|||||||
getChecksParamValidation,
|
getChecksParamValidation,
|
||||||
getChecksQueryValidation,
|
getChecksQueryValidation,
|
||||||
getTeamChecksQueryValidation,
|
getTeamChecksQueryValidation,
|
||||||
|
getChecksSummaryByTeamIdQueryValidation,
|
||||||
deleteChecksParamValidation,
|
deleteChecksParamValidation,
|
||||||
deleteChecksByTeamIdParamValidation,
|
|
||||||
updateChecksTTLBodyValidation,
|
|
||||||
} from "@/validation/checkValidation.js";
|
} from "@/validation/checkValidation.js";
|
||||||
|
import { ICheckService } from "@/service/index.js";
|
||||||
|
import { requireTeamId } from "@/controllers/controllerUtils.js";
|
||||||
|
|
||||||
const SERVICE_NAME = "checkController";
|
const SERVICE_NAME = "checkController";
|
||||||
|
|
||||||
class CheckController {
|
class CheckController {
|
||||||
static SERVICE_NAME = SERVICE_NAME;
|
static SERVICE_NAME = SERVICE_NAME;
|
||||||
|
|
||||||
private checkService: any;
|
private checkService: ICheckService;
|
||||||
constructor(checkService: any) {
|
constructor(checkService: ICheckService) {
|
||||||
this.checkService = checkService;
|
this.checkService = checkService;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -25,13 +26,20 @@ class CheckController {
|
|||||||
|
|
||||||
getChecksByMonitor = async (req: Request, res: Response, next: NextFunction) => {
|
getChecksByMonitor = async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
getChecksParamValidation.parse(req.params);
|
const validatedParams = getChecksParamValidation.parse(req.params);
|
||||||
getChecksQueryValidation.parse(req.query);
|
const validatedQuery = getChecksQueryValidation.parse(req.query);
|
||||||
|
|
||||||
|
const teamId = requireTeamId(req.user?.teamId);
|
||||||
|
|
||||||
const result = await this.checkService.getChecksByMonitor({
|
const result = await this.checkService.getChecksByMonitor({
|
||||||
monitorId: req?.params?.monitorId,
|
monitorId: validatedParams.monitorId,
|
||||||
query: req?.query,
|
teamId,
|
||||||
teamId: req?.user?.teamId,
|
sortOrder: validatedQuery.sortOrder,
|
||||||
|
dateRange: validatedQuery.dateRange,
|
||||||
|
filter: validatedQuery.filter,
|
||||||
|
page: validatedQuery.page,
|
||||||
|
rowsPerPage: validatedQuery.rowsPerPage,
|
||||||
|
status: validatedQuery.status,
|
||||||
});
|
});
|
||||||
|
|
||||||
return res.status(200).json({
|
return res.status(200).json({
|
||||||
@@ -46,10 +54,16 @@ class CheckController {
|
|||||||
|
|
||||||
getChecksByTeam = async (req: Request, res: Response, next: NextFunction) => {
|
getChecksByTeam = async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
getTeamChecksQueryValidation.parse(req.query);
|
const validatedQuery = getTeamChecksQueryValidation.parse(req.query);
|
||||||
|
const teamId = requireTeamId(req.user?.teamId);
|
||||||
|
|
||||||
const checkData = await this.checkService.getChecksByTeam({
|
const checkData = await this.checkService.getChecksByTeam({
|
||||||
teamId: req?.user?.teamId,
|
teamId,
|
||||||
query: req?.query,
|
sortOrder: validatedQuery.sortOrder,
|
||||||
|
dateRange: validatedQuery.dateRange,
|
||||||
|
page: validatedQuery.page,
|
||||||
|
rowsPerPage: validatedQuery.rowsPerPage,
|
||||||
|
filter: validatedQuery.filter,
|
||||||
});
|
});
|
||||||
return res.status(200).json({
|
return res.status(200).json({
|
||||||
success: true,
|
success: true,
|
||||||
@@ -63,8 +77,11 @@ class CheckController {
|
|||||||
|
|
||||||
getChecksSummaryByTeamId = async (req: Request, res: Response, next: NextFunction) => {
|
getChecksSummaryByTeamId = async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
const dateRange = req.query?.dateRange || "hour";
|
const validatedQuery = getChecksSummaryByTeamIdQueryValidation.parse(req.query);
|
||||||
const summary = await this.checkService.getChecksSummaryByTeamId({ teamId: req?.user?.teamId, dateRange });
|
const teamId = requireTeamId(req.user?.teamId);
|
||||||
|
const dateRange = validatedQuery.dateRange ?? "hour";
|
||||||
|
|
||||||
|
const summary = await this.checkService.getChecksSummaryByTeamId({ teamId, dateRange });
|
||||||
return res.status(200).json({
|
return res.status(200).json({
|
||||||
success: true,
|
success: true,
|
||||||
msg: "Checks summary retrieved successfully",
|
msg: "Checks summary retrieved successfully",
|
||||||
@@ -77,11 +94,12 @@ class CheckController {
|
|||||||
|
|
||||||
deleteChecks = async (req: Request, res: Response, next: NextFunction) => {
|
deleteChecks = async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
deleteChecksParamValidation.parse(req.params);
|
const validatedParams = deleteChecksParamValidation.parse(req.params);
|
||||||
|
const teamId = requireTeamId(req.user?.teamId);
|
||||||
|
|
||||||
const deletedCount = await this.checkService.deleteChecks({
|
const deletedCount = await this.checkService.deleteChecks({
|
||||||
monitorId: req.params.monitorId as string,
|
monitorId: validatedParams.monitorId,
|
||||||
teamId: req?.user?.teamId,
|
teamId,
|
||||||
});
|
});
|
||||||
|
|
||||||
return res.status(200).json({
|
return res.status(200).json({
|
||||||
@@ -96,9 +114,9 @@ class CheckController {
|
|||||||
|
|
||||||
deleteChecksByTeamId = async (req: Request, res: Response, next: NextFunction) => {
|
deleteChecksByTeamId = async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
deleteChecksByTeamIdParamValidation.parse(req.params);
|
const teamId = requireTeamId(req.user?.teamId);
|
||||||
|
|
||||||
const deletedCount = await this.checkService.deleteChecksByTeamId({ teamId: req?.user?.teamId });
|
const deletedCount = await this.checkService.deleteChecksByTeamId({ teamId });
|
||||||
|
|
||||||
return res.status(200).json({
|
return res.status(200).json({
|
||||||
success: true,
|
success: true,
|
||||||
@@ -109,24 +127,6 @@ class CheckController {
|
|||||||
next(error);
|
next(error);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
updateChecksTTL = async (req: Request, res: Response, next: NextFunction) => {
|
|
||||||
try {
|
|
||||||
updateChecksTTLBodyValidation.parse(req.body);
|
|
||||||
|
|
||||||
await this.checkService.updateChecksTTL({
|
|
||||||
teamId: req?.user?.teamId,
|
|
||||||
ttl: req?.body?.ttl,
|
|
||||||
});
|
|
||||||
|
|
||||||
return res.status(200).json({
|
|
||||||
success: true,
|
|
||||||
msg: "Checks TTL updated successfully",
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
next(error);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export default CheckController;
|
export default CheckController;
|
||||||
@@ -1,11 +1,12 @@
|
|||||||
import { AppError } from "@/utils/AppError.js";
|
import { AppError } from "@/utils/AppError.js";
|
||||||
import { type MonitorType, MonitorTypes } from "@/types/index.js";
|
import { Monitor, type MonitorType, MonitorTypes, UserRole } from "@/types/index.js";
|
||||||
|
import sslChecker, { SSLDetails } from "ssl-checker";
|
||||||
|
type SSLCheckerType = typeof sslChecker;
|
||||||
|
|
||||||
const fetchMonitorCertificate = async (sslChecker: any, monitor: any): Promise<any> => {
|
const fetchMonitorCertificate = async (checker: SSLCheckerType, monitor: Monitor): Promise<SSLDetails> => {
|
||||||
const monitorUrl = new URL(monitor.url);
|
const monitorUrl = new URL(monitor.url);
|
||||||
const hostname = monitorUrl.hostname;
|
const hostname = monitorUrl.hostname;
|
||||||
const cert = await sslChecker(hostname);
|
const cert = await checker(hostname);
|
||||||
// Throw an error if no cert or if cert.validTo is not present
|
|
||||||
if (cert?.validTo === null || cert?.validTo === undefined) {
|
if (cert?.validTo === null || cert?.validTo === undefined) {
|
||||||
throw new Error("Certificate not found");
|
throw new Error("Certificate not found");
|
||||||
}
|
}
|
||||||
@@ -112,7 +113,7 @@ const requireUserEmail = (userEmail?: string): string => {
|
|||||||
return userEmail;
|
return userEmail;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const requireUserRoles = (userRoles?: string[]): string[] => {
|
export const requireUserRoles = (userRoles?: UserRole[]): UserRole[] => {
|
||||||
if (!userRoles || userRoles.length === 0) {
|
if (!userRoles || userRoles.length === 0) {
|
||||||
throw new AppError({ message: "User roles are required", status: 400 });
|
throw new AppError({ message: "User roles are required", status: 400 });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,13 @@
|
|||||||
|
import { IDiagnosticService } from "@/service/index.js";
|
||||||
import { Request, Response, NextFunction } from "express";
|
import { Request, Response, NextFunction } from "express";
|
||||||
|
|
||||||
const SERVICE_NAME = "diagnosticController";
|
const SERVICE_NAME = "diagnosticController";
|
||||||
class DiagnosticController {
|
class DiagnosticController {
|
||||||
static SERVICE_NAME = SERVICE_NAME;
|
static SERVICE_NAME = SERVICE_NAME;
|
||||||
|
|
||||||
private diagnosticService: any;
|
private diagnosticService: IDiagnosticService;
|
||||||
|
|
||||||
constructor(diagnosticService: any) {
|
constructor(diagnosticService: IDiagnosticService) {
|
||||||
this.diagnosticService = diagnosticService;
|
this.diagnosticService = diagnosticService;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
import mongoose from "mongoose";
|
||||||
|
import { logger } from "@/utils/logger.js";
|
||||||
|
import StatusPageModel from "../models/StatusPage.js";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Migration: Convert StatusPage `type` field from string to array of strings
|
||||||
|
*
|
||||||
|
* Old format: { type: "uptime" }
|
||||||
|
* New format: { type: ["uptime"] }
|
||||||
|
*/
|
||||||
|
export async function migrateStatusPageTypeToArray(): Promise<void> {
|
||||||
|
const SERVICE_NAME = "Migration:MigrateStatusPageTypeToArray";
|
||||||
|
|
||||||
|
try {
|
||||||
|
logger.info({ service: SERVICE_NAME, message: "Starting migration of StatusPage type field from string to array" });
|
||||||
|
|
||||||
|
const db = mongoose.connection.db;
|
||||||
|
if (!db) {
|
||||||
|
throw new Error("Database connection is not initialized");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Find all status pages where `type` is a string (not yet migrated)
|
||||||
|
const result = await StatusPageModel.updateMany(
|
||||||
|
{
|
||||||
|
$expr: {
|
||||||
|
$eq: [{ $type: "$type" }, "string"], // only scalar string, not existing array
|
||||||
|
},
|
||||||
|
},
|
||||||
|
[
|
||||||
|
{
|
||||||
|
$set: {
|
||||||
|
type: ["$type"],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]
|
||||||
|
);
|
||||||
|
|
||||||
|
if (result.modifiedCount === 0) {
|
||||||
|
logger.info({ service: SERVICE_NAME, message: "No StatusPage documents needed migration" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info({
|
||||||
|
service: SERVICE_NAME,
|
||||||
|
message: `Migration complete. Converted ${result.modifiedCount} StatusPage document(s) from string type to array type`,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||||
|
logger.error({ service: SERVICE_NAME, message: `Error during StatusPage type migration: ${errorMessage}` });
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ import { convertChecksToTimeSeries } from "./0002_convertChecksToTimeSeries.js";
|
|||||||
import { cleanupDuplicateMonitorStats } from "./0003_cleanupDuplicateMonitorStats.js";
|
import { cleanupDuplicateMonitorStats } from "./0003_cleanupDuplicateMonitorStats.js";
|
||||||
import { fixInfrastructureThresholds } from "./0004_fixInfrastructureThresholds.js";
|
import { fixInfrastructureThresholds } from "./0004_fixInfrastructureThresholds.js";
|
||||||
import MigrationModel from "../models/Migration.js";
|
import MigrationModel from "../models/Migration.js";
|
||||||
|
import { migrateStatusPageTypeToArray } from "./0005_migrateStatusPageTypeToArray.js";
|
||||||
|
|
||||||
type MigrationEntry = {
|
type MigrationEntry = {
|
||||||
name: string;
|
name: string;
|
||||||
@@ -14,6 +15,7 @@ const migrations: MigrationEntry[] = [
|
|||||||
{ name: "0002_convertChecksToTimeSeries", execute: convertChecksToTimeSeries },
|
{ name: "0002_convertChecksToTimeSeries", execute: convertChecksToTimeSeries },
|
||||||
{ name: "0003_cleanupDuplicateMonitorStats", execute: cleanupDuplicateMonitorStats },
|
{ name: "0003_cleanupDuplicateMonitorStats", execute: cleanupDuplicateMonitorStats },
|
||||||
{ name: "0004_fixInfrastructureThresholds", execute: fixInfrastructureThresholds },
|
{ name: "0004_fixInfrastructureThresholds", execute: fixInfrastructureThresholds },
|
||||||
|
{ name: "0005_migrateStatusPageTypeToArray", execute: migrateStatusPageTypeToArray },
|
||||||
];
|
];
|
||||||
|
|
||||||
const runMigrations = async (logger?: { info: Function; error: Function }) => {
|
const runMigrations = async (logger?: { info: Function; error: Function }) => {
|
||||||
|
|||||||
@@ -21,13 +21,10 @@ type CheckMetadataDocument = Omit<CheckMetadata, "monitorId" | "teamId"> & {
|
|||||||
type: MonitorType;
|
type: MonitorType;
|
||||||
};
|
};
|
||||||
|
|
||||||
type CheckDocumentBase = Omit<Check, "id" | "metadata" | "expiry" | "ackAt" | "createdAt" | "updatedAt"> & {
|
type CheckDocumentBase = Omit<Check, "id" | "metadata" | "createdAt" | "updatedAt"> & {
|
||||||
metadata: CheckMetadataDocument;
|
metadata: CheckMetadataDocument;
|
||||||
expiry: Date;
|
|
||||||
ackAt?: Date | null;
|
|
||||||
createdAt: Date;
|
createdAt: Date;
|
||||||
updatedAt: Date;
|
updatedAt: Date;
|
||||||
__v: number;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
interface CheckDocument extends CheckDocumentBase {
|
interface CheckDocument extends CheckDocumentBase {
|
||||||
@@ -225,18 +222,7 @@ const CheckSchema = new Schema<CheckDocument>(
|
|||||||
message: {
|
message: {
|
||||||
type: String,
|
type: String,
|
||||||
},
|
},
|
||||||
expiry: {
|
|
||||||
type: Date,
|
|
||||||
default: Date.now,
|
|
||||||
},
|
|
||||||
ack: {
|
|
||||||
type: Boolean,
|
|
||||||
default: false,
|
|
||||||
},
|
|
||||||
ackAt: {
|
|
||||||
type: Date,
|
|
||||||
default: undefined,
|
|
||||||
},
|
|
||||||
cpu: {
|
cpu: {
|
||||||
type: cpuSchema,
|
type: cpuSchema,
|
||||||
default: () => ({}),
|
default: () => ({}),
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ const NotificationSchema = new Schema<NotificationDocument>(
|
|||||||
},
|
},
|
||||||
type: {
|
type: {
|
||||||
type: String,
|
type: String,
|
||||||
enum: ["email", "slack", "discord", "webhook", "pager_duty", "matrix"] as NotificationChannel[],
|
enum: ["email", "slack", "discord", "webhook", "pager_duty", "matrix", "teams"] as NotificationChannel[],
|
||||||
required: true,
|
required: true,
|
||||||
},
|
},
|
||||||
notificationName: {
|
notificationName: {
|
||||||
|
|||||||
@@ -43,9 +43,9 @@ const StatusPageSchema = new Schema<StatusPageDocument>(
|
|||||||
required: true,
|
required: true,
|
||||||
},
|
},
|
||||||
type: {
|
type: {
|
||||||
type: String,
|
type: [String],
|
||||||
required: true,
|
required: true,
|
||||||
default: "uptime",
|
default: [],
|
||||||
enum: StatusPageTypes,
|
enum: StatusPageTypes,
|
||||||
},
|
},
|
||||||
companyName: {
|
companyName: {
|
||||||
@@ -100,6 +100,10 @@ const StatusPageSchema = new Schema<StatusPageDocument>(
|
|||||||
type: Boolean,
|
type: Boolean,
|
||||||
default: false,
|
default: false,
|
||||||
},
|
},
|
||||||
|
showInfrastructure: {
|
||||||
|
type: Boolean,
|
||||||
|
default: false,
|
||||||
|
},
|
||||||
customCSS: {
|
customCSS: {
|
||||||
type: String,
|
type: String,
|
||||||
default: "",
|
default: "",
|
||||||
|
|||||||
@@ -47,4 +47,5 @@ export interface IChecksRepository {
|
|||||||
deleteByMonitorId(monitorId: string): Promise<number>;
|
deleteByMonitorId(monitorId: string): Promise<number>;
|
||||||
deleteByTeamId(teamId: string): Promise<number>;
|
deleteByTeamId(teamId: string): Promise<number>;
|
||||||
deleteByMonitorIdsNotIn(monitorIds: string[]): Promise<number>;
|
deleteByMonitorIdsNotIn(monitorIds: string[]): Promise<number>;
|
||||||
|
deleteOlderThan(date: Date): Promise<number>;
|
||||||
}
|
}
|
||||||
@@ -13,9 +13,10 @@ import type {
|
|||||||
GotTimings,
|
GotTimings,
|
||||||
MonitorType,
|
MonitorType,
|
||||||
} from "@/types/index.js";
|
} from "@/types/index.js";
|
||||||
import { CheckModel, MonitorModel, type CheckDocument } from "@/db/models/index.js";
|
import { CheckModel, type CheckDocument } from "@/db/models/index.js";
|
||||||
import mongoose from "mongoose";
|
import mongoose from "mongoose";
|
||||||
import { getDateForRange } from "@/utils/dataUtils.js";
|
import { getDateForRange } from "@/utils/dataUtils.js";
|
||||||
|
import { ILogger } from "@/utils/logger.js";
|
||||||
|
|
||||||
const SERVICE_NAME = "StatusService";
|
const SERVICE_NAME = "StatusService";
|
||||||
|
|
||||||
@@ -26,8 +27,8 @@ type HardwareUpChecks = { totalChecks: number };
|
|||||||
class MongoChecksRepository implements IChecksRepository {
|
class MongoChecksRepository implements IChecksRepository {
|
||||||
static SERVICE_NAME = SERVICE_NAME;
|
static SERVICE_NAME = SERVICE_NAME;
|
||||||
|
|
||||||
private logger: any;
|
private logger: ILogger;
|
||||||
constructor(logger: any) {
|
constructor(logger: ILogger) {
|
||||||
this.logger = logger;
|
this.logger = logger;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -46,13 +47,6 @@ class MongoChecksRepository implements IChecksRepository {
|
|||||||
return value instanceof Date ? value.toISOString() : new Date(value).toISOString();
|
return value instanceof Date ? value.toISOString() : new Date(value).toISOString();
|
||||||
};
|
};
|
||||||
|
|
||||||
const toOptionalDateString = (value?: Date | string | null): string | undefined => {
|
|
||||||
if (!value) {
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
return toDateString(value);
|
|
||||||
};
|
|
||||||
|
|
||||||
const mapTimings = (timings?: GotTimings): GotTimings => {
|
const mapTimings = (timings?: GotTimings): GotTimings => {
|
||||||
const phases = timings?.phases ?? {
|
const phases = timings?.phases ?? {
|
||||||
wait: 0,
|
wait: 0,
|
||||||
@@ -171,9 +165,6 @@ class MongoChecksRepository implements IChecksRepository {
|
|||||||
timings: mapTimings(doc.timings),
|
timings: mapTimings(doc.timings),
|
||||||
statusCode: doc.statusCode ?? 0,
|
statusCode: doc.statusCode ?? 0,
|
||||||
message: doc.message ?? "",
|
message: doc.message ?? "",
|
||||||
ack: doc.ack ?? false,
|
|
||||||
ackAt: toOptionalDateString(doc.ackAt),
|
|
||||||
expiry: toDateString(doc.expiry),
|
|
||||||
cpu: mapCpu(doc.cpu),
|
cpu: mapCpu(doc.cpu),
|
||||||
memory: mapMemory(doc.memory),
|
memory: mapMemory(doc.memory),
|
||||||
disk: mapDisks(doc.disk),
|
disk: mapDisks(doc.disk),
|
||||||
@@ -186,7 +177,6 @@ class MongoChecksRepository implements IChecksRepository {
|
|||||||
seo: doc.seo,
|
seo: doc.seo,
|
||||||
performance: doc.performance,
|
performance: doc.performance,
|
||||||
audits: mapAudits(doc.audits),
|
audits: mapAudits(doc.audits),
|
||||||
__v: doc.__v ?? 0,
|
|
||||||
createdAt: toDateString(doc.createdAt),
|
createdAt: toDateString(doc.createdAt),
|
||||||
updatedAt: toDateString(doc.updatedAt),
|
updatedAt: toDateString(doc.updatedAt),
|
||||||
};
|
};
|
||||||
@@ -237,7 +227,7 @@ class MongoChecksRepository implements IChecksRepository {
|
|||||||
status: boolean | undefined
|
status: boolean | undefined
|
||||||
) => {
|
) => {
|
||||||
// Match
|
// Match
|
||||||
const matchStage: Record<string, any> = {
|
const matchStage: Record<string, unknown> = {
|
||||||
"metadata.monitorId": new mongoose.Types.ObjectId(monitorId),
|
"metadata.monitorId": new mongoose.Types.ObjectId(monitorId),
|
||||||
...(typeof status !== "undefined" && { status }),
|
...(typeof status !== "undefined" && { status }),
|
||||||
...(getDateForRange(dateRange) && {
|
...(getDateForRange(dateRange) && {
|
||||||
@@ -289,7 +279,7 @@ class MongoChecksRepository implements IChecksRepository {
|
|||||||
};
|
};
|
||||||
|
|
||||||
findByTeamId = async (sortOrder: string, dateRange: string, filter: string, page: number, rowsPerPage: number, teamId: string) => {
|
findByTeamId = async (sortOrder: string, dateRange: string, filter: string, page: number, rowsPerPage: number, teamId: string) => {
|
||||||
const matchStage: Record<string, any> = {
|
const matchStage: Record<string, unknown> = {
|
||||||
"metadata.teamId": new mongoose.Types.ObjectId(teamId),
|
"metadata.teamId": new mongoose.Types.ObjectId(teamId),
|
||||||
...(getDateForRange(dateRange) && {
|
...(getDateForRange(dateRange) && {
|
||||||
createdAt: {
|
createdAt: {
|
||||||
@@ -358,7 +348,7 @@ class MongoChecksRepository implements IChecksRepository {
|
|||||||
);
|
);
|
||||||
|
|
||||||
const mapped = results.reduce<LatestChecksMap>((acc, { monitorId, docs }) => {
|
const mapped = results.reduce<LatestChecksMap>((acc, { monitorId, docs }) => {
|
||||||
acc[monitorId] = docs.map((doc: any) => this.toEntity(doc as CheckDocument));
|
acc[monitorId] = docs.map((doc: CheckDocument) => this.toEntity(doc));
|
||||||
return acc;
|
return acc;
|
||||||
}, {});
|
}, {});
|
||||||
return mapped;
|
return mapped;
|
||||||
@@ -412,6 +402,31 @@ class MongoChecksRepository implements IChecksRepository {
|
|||||||
return result.deletedCount ?? 0;
|
return result.deletedCount ?? 0;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
deleteOlderThan = async (cutoffDate: Date, batchDays: number = 30): Promise<number> => {
|
||||||
|
// Find the oldest check that is older than the cutoff
|
||||||
|
const oldest = await CheckModel.findOne({ createdAt: { $lt: cutoffDate } })
|
||||||
|
.sort({ createdAt: 1 })
|
||||||
|
.select({ createdAt: 1 });
|
||||||
|
if (!oldest?.createdAt) return 0;
|
||||||
|
|
||||||
|
let totalDeleted = 0;
|
||||||
|
let batchStart = new Date(oldest.createdAt);
|
||||||
|
const batchMs = batchDays * 24 * 60 * 60 * 1000;
|
||||||
|
|
||||||
|
// Delete in 30 day chunks until we reach the cutoff
|
||||||
|
while (batchStart < cutoffDate) {
|
||||||
|
// Advance startTime by batchMs to get to the end of last batch
|
||||||
|
const nextStart = batchStart.getTime() + batchMs;
|
||||||
|
const batchEnd = new Date(Math.min(nextStart, cutoffDate.getTime()));
|
||||||
|
const result = await CheckModel.deleteMany({
|
||||||
|
createdAt: { $gte: batchStart, $lt: batchEnd },
|
||||||
|
});
|
||||||
|
totalDeleted += result.deletedCount ?? 0;
|
||||||
|
batchStart = batchEnd;
|
||||||
|
}
|
||||||
|
|
||||||
|
return totalDeleted;
|
||||||
|
};
|
||||||
private findUptimeDateRangeChecks = async (
|
private findUptimeDateRangeChecks = async (
|
||||||
monitorType: Exclude<MonitorType, "hardware" | "pagespeed">,
|
monitorType: Exclude<MonitorType, "hardware" | "pagespeed">,
|
||||||
monitorObjectId: mongoose.Types.ObjectId,
|
monitorObjectId: mongoose.Types.ObjectId,
|
||||||
|
|||||||
@@ -57,6 +57,7 @@ class MongoStatusPagesRepository implements IStatusPagesRepository {
|
|||||||
showCharts: doc.showCharts,
|
showCharts: doc.showCharts,
|
||||||
showUptimePercentage: doc.showUptimePercentage,
|
showUptimePercentage: doc.showUptimePercentage,
|
||||||
showAdminLoginLink: doc.showAdminLoginLink,
|
showAdminLoginLink: doc.showAdminLoginLink,
|
||||||
|
showInfrastructure: doc.showInfrastructure,
|
||||||
customCSS: doc.customCSS,
|
customCSS: doc.customCSS,
|
||||||
createdAt: this.toDateString(doc.createdAt),
|
createdAt: this.toDateString(doc.createdAt),
|
||||||
updatedAt: this.toDateString(doc.updatedAt),
|
updatedAt: this.toDateString(doc.updatedAt),
|
||||||
|
|||||||
@@ -15,7 +15,6 @@ class CheckRoutes {
|
|||||||
initRoutes() {
|
initRoutes() {
|
||||||
this.router.get("/team/summary", this.checkController.getChecksSummaryByTeamId);
|
this.router.get("/team/summary", this.checkController.getChecksSummaryByTeamId);
|
||||||
this.router.get("/team", this.checkController.getChecksByTeam);
|
this.router.get("/team", this.checkController.getChecksByTeam);
|
||||||
this.router.put("/team/ttl", isAllowed(["admin", "superadmin"]), this.checkController.updateChecksTTL);
|
|
||||||
this.router.delete("/team", isAllowed(["admin", "superadmin"]), this.checkController.deleteChecksByTeamId);
|
this.router.delete("/team", isAllowed(["admin", "superadmin"]), this.checkController.deleteChecksByTeamId);
|
||||||
this.router.get("/:monitorId", this.checkController.getChecksByMonitor);
|
this.router.get("/:monitorId", this.checkController.getChecksByMonitor);
|
||||||
this.router.delete("/:monitorId", this.checkController.deleteChecks);
|
this.router.delete("/:monitorId", this.checkController.deleteChecks);
|
||||||
|
|||||||
@@ -1,22 +1,45 @@
|
|||||||
import { Types } from "mongoose";
|
import { Types } from "mongoose";
|
||||||
import { IChecksRepository, IMonitorsRepository } from "@/repositories/index.js";
|
import { IChecksRepository, IMonitorsRepository } from "@/repositories/index.js";
|
||||||
import type { MonitorStatusResponse, CheckErrorInfo, Check, ILighthouseAudit, ChecksQueryResult, ChecksSummary } from "@/types/index.js";
|
import type {
|
||||||
|
MonitorStatusResponse,
|
||||||
|
CheckErrorInfo,
|
||||||
|
Check,
|
||||||
|
ILighthouseAudit,
|
||||||
|
ChecksQueryResult,
|
||||||
|
ChecksSummary,
|
||||||
|
MonitorPayloadMap,
|
||||||
|
} from "@/types/index.js";
|
||||||
import type { HardwareStatusPayload, PageSpeedStatusPayload } from "@/types/network.js";
|
import type { HardwareStatusPayload, PageSpeedStatusPayload } from "@/types/network.js";
|
||||||
import { AppError } from "@/utils/AppError.js";
|
import { AppError } from "@/utils/AppError.js";
|
||||||
import { ParseBoolean } from "@/utils/utils.js";
|
|
||||||
import { ILogger } from "@/utils/logger.js";
|
import { ILogger } from "@/utils/logger.js";
|
||||||
|
|
||||||
const SERVICE_NAME = "checkService";
|
const SERVICE_NAME = "checkService";
|
||||||
|
|
||||||
export interface ICheckService {
|
export interface ICheckService {
|
||||||
createChecks(checks: Check[]): Promise<Check[]>;
|
createChecks(checks: Check[]): Promise<Check[]>;
|
||||||
buildCheck(statusResponse: MonitorStatusResponse<PageSpeedStatusPayload | HardwareStatusPayload | undefined>): Partial<Check> | undefined;
|
buildCheck(statusResponse: MonitorStatusResponse<MonitorPayloadMap[keyof MonitorPayloadMap]>): Check | undefined;
|
||||||
getChecksByMonitor(params: { monitorId: string; query: Record<string, string>; teamId: string }): Promise<ChecksQueryResult>;
|
getChecksByMonitor(params: {
|
||||||
getChecksByTeam(params: { teamId: string; query: Record<string, string> }): Promise<ChecksQueryResult>;
|
monitorId: string;
|
||||||
|
teamId: string;
|
||||||
|
sortOrder: string;
|
||||||
|
dateRange: string;
|
||||||
|
page: number;
|
||||||
|
rowsPerPage: number;
|
||||||
|
filter?: string;
|
||||||
|
status?: boolean;
|
||||||
|
}): Promise<ChecksQueryResult>;
|
||||||
|
getChecksByTeam(params: {
|
||||||
|
teamId: string;
|
||||||
|
sortOrder: string;
|
||||||
|
dateRange: string;
|
||||||
|
page: number;
|
||||||
|
rowsPerPage: number;
|
||||||
|
filter?: string;
|
||||||
|
}): Promise<ChecksQueryResult>;
|
||||||
getChecksSummaryByTeamId(params: { teamId: string; dateRange: string }): Promise<ChecksSummary>;
|
getChecksSummaryByTeamId(params: { teamId: string; dateRange: string }): Promise<ChecksSummary>;
|
||||||
deleteChecks(params: { monitorId: string; teamId: string }): Promise<number>;
|
deleteChecks(params: { monitorId: string; teamId: string }): Promise<number>;
|
||||||
deleteChecksByTeamId(params: { teamId: string }): Promise<number>;
|
deleteChecksByTeamId(params: { teamId: string }): Promise<number>;
|
||||||
updateChecksTTL(params: { teamId: string; ttl: string }): Promise<void>;
|
deleteOlderThan(date: Date): Promise<number>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class CheckService implements ICheckService {
|
export class CheckService implements ICheckService {
|
||||||
@@ -39,12 +62,14 @@ export class CheckService implements ICheckService {
|
|||||||
return this.checksRepository.createChecks(checks);
|
return this.checksRepository.createChecks(checks);
|
||||||
};
|
};
|
||||||
|
|
||||||
buildCheck = (statusResponse: MonitorStatusResponse<PageSpeedStatusPayload | HardwareStatusPayload | undefined>) => {
|
buildCheck = (statusResponse: MonitorStatusResponse<MonitorPayloadMap[keyof MonitorPayloadMap]>): Check | undefined => {
|
||||||
const { monitorId, teamId, type, status, responseTime, code, message, payload, timings } = statusResponse;
|
const { monitorId, teamId, type, status, responseTime, code, message, payload, timings } = statusResponse;
|
||||||
|
|
||||||
const check: Partial<Check> = {
|
const now = new Date().toISOString();
|
||||||
|
const check: Check = {
|
||||||
id: new Types.ObjectId().toString(),
|
id: new Types.ObjectId().toString(),
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: now,
|
||||||
|
updatedAt: now,
|
||||||
metadata: {
|
metadata: {
|
||||||
monitorId,
|
monitorId,
|
||||||
teamId,
|
teamId,
|
||||||
@@ -112,7 +137,25 @@ export class CheckService implements ICheckService {
|
|||||||
return check;
|
return check;
|
||||||
};
|
};
|
||||||
|
|
||||||
getChecksByMonitor = async ({ monitorId, query, teamId }: { monitorId: string; query: Record<string, string>; teamId: string }) => {
|
getChecksByMonitor = async ({
|
||||||
|
monitorId,
|
||||||
|
teamId,
|
||||||
|
sortOrder,
|
||||||
|
dateRange,
|
||||||
|
filter,
|
||||||
|
page,
|
||||||
|
rowsPerPage,
|
||||||
|
status,
|
||||||
|
}: {
|
||||||
|
monitorId: string;
|
||||||
|
teamId: string;
|
||||||
|
sortOrder: string;
|
||||||
|
dateRange: string;
|
||||||
|
page: number;
|
||||||
|
rowsPerPage: number;
|
||||||
|
status?: boolean;
|
||||||
|
filter?: string;
|
||||||
|
}) => {
|
||||||
if (!monitorId) {
|
if (!monitorId) {
|
||||||
throw new AppError({ message: "No monitor ID in request", service: SERVICE_NAME, method: "getChecksByMonitor", status: 400 });
|
throw new AppError({ message: "No monitor ID in request", service: SERVICE_NAME, method: "getChecksByMonitor", status: 400 });
|
||||||
}
|
}
|
||||||
@@ -123,74 +166,54 @@ export class CheckService implements ICheckService {
|
|||||||
// For verification, throws an error if monitor doesn't belong to team
|
// For verification, throws an error if monitor doesn't belong to team
|
||||||
await this.monitorsRepository.findById(monitorId, teamId);
|
await this.monitorsRepository.findById(monitorId, teamId);
|
||||||
|
|
||||||
const { sortOrder, dateRange, filter, page, rowsPerPage, status } = query;
|
const parsedPage = page ?? 0;
|
||||||
if (!sortOrder || !dateRange || !page || !rowsPerPage) {
|
const parsedRowsPerPage = rowsPerPage ?? 5;
|
||||||
throw new AppError({
|
|
||||||
message: `Missing required query parameters sortOrder: ${sortOrder}, dateRange: ${dateRange}, filter: ${filter}, page: ${page}, rowsPerPage: ${rowsPerPage}`,
|
|
||||||
service: SERVICE_NAME,
|
|
||||||
method: "getChecksByMonitor",
|
|
||||||
status: 400,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
const parsedStatus = typeof status === "undefined" ? status : ParseBoolean(status);
|
|
||||||
const parsedPage = page ? parseInt(page) : 0;
|
|
||||||
const parsedRowsPerPage = rowsPerPage ? parseInt(rowsPerPage) : 5;
|
|
||||||
|
|
||||||
const result = await this.checksRepository.findByMonitorId(monitorId, sortOrder, dateRange, filter, parsedPage, parsedRowsPerPage, parsedStatus);
|
const result = await this.checksRepository.findByMonitorId(monitorId, sortOrder, dateRange, filter, parsedPage, parsedRowsPerPage, status);
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
};
|
};
|
||||||
|
|
||||||
getChecksByTeam = async ({ teamId, query }: { teamId: string; query: Record<string, string> }) => {
|
getChecksByTeam = async ({
|
||||||
const { sortOrder, dateRange, filter, page, rowsPerPage } = query;
|
teamId,
|
||||||
if (!sortOrder || !dateRange || !page || !rowsPerPage) {
|
sortOrder,
|
||||||
throw new AppError({ message: "Missing required query parameters", service: SERVICE_NAME, method: "getChecksByTeam", status: 400 });
|
dateRange,
|
||||||
}
|
filter,
|
||||||
|
page,
|
||||||
if (!teamId) {
|
rowsPerPage,
|
||||||
throw new AppError({ message: "No team ID in request", service: SERVICE_NAME, method: "getChecksByTeam", status: 400 });
|
}: {
|
||||||
}
|
teamId: string;
|
||||||
|
sortOrder: string;
|
||||||
const parsedPage = page ? parseInt(page) : 0;
|
dateRange: string;
|
||||||
const parsedRowsPerPage = rowsPerPage ? parseInt(rowsPerPage) : 5;
|
page: number;
|
||||||
|
rowsPerPage: number;
|
||||||
|
filter?: string;
|
||||||
|
}) => {
|
||||||
|
const parsedPage = page ?? 0;
|
||||||
|
const parsedRowsPerPage = rowsPerPage ?? 5;
|
||||||
|
|
||||||
const checkData = await this.checksRepository.findByTeamId(sortOrder, dateRange, filter, parsedPage, parsedRowsPerPage, teamId);
|
const checkData = await this.checksRepository.findByTeamId(sortOrder, dateRange, filter, parsedPage, parsedRowsPerPage, teamId);
|
||||||
return checkData;
|
return checkData;
|
||||||
};
|
};
|
||||||
|
|
||||||
getChecksSummaryByTeamId = async ({ teamId, dateRange }: { teamId: string; dateRange: string }) => {
|
getChecksSummaryByTeamId = async ({ teamId, dateRange }: { teamId: string; dateRange: string }) => {
|
||||||
if (!teamId) {
|
|
||||||
throw new AppError({ message: "No team ID in request", service: SERVICE_NAME, method: "getChecksSummaryByTeamId", status: 400 });
|
|
||||||
}
|
|
||||||
const summary = await this.checksRepository.findSummaryByTeamId(teamId, dateRange);
|
const summary = await this.checksRepository.findSummaryByTeamId(teamId, dateRange);
|
||||||
return summary;
|
return summary;
|
||||||
};
|
};
|
||||||
|
|
||||||
deleteChecks = async ({ monitorId, teamId }: { monitorId: string; teamId: string }) => {
|
deleteChecks = async ({ monitorId, teamId }: { monitorId: string; teamId: string }) => {
|
||||||
if (!monitorId) {
|
|
||||||
throw new AppError({ message: "No monitor ID in request", service: SERVICE_NAME, method: "deleteChecks", status: 400 });
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!teamId) {
|
|
||||||
throw new AppError({ message: "No team ID in request", service: SERVICE_NAME, method: "deleteChecks", status: 400 });
|
|
||||||
}
|
|
||||||
|
|
||||||
// For verification, throws an error if monitor doesn't belong to team
|
|
||||||
await this.monitorsRepository.findById(monitorId, teamId);
|
await this.monitorsRepository.findById(monitorId, teamId);
|
||||||
|
|
||||||
const deletedCount = await this.checksRepository.deleteByMonitorId(monitorId);
|
const deletedCount = await this.checksRepository.deleteByMonitorId(monitorId);
|
||||||
return deletedCount;
|
return deletedCount;
|
||||||
};
|
};
|
||||||
deleteChecksByTeamId = async ({ teamId }: { teamId: string }) => {
|
deleteChecksByTeamId = async ({ teamId }: { teamId: string }) => {
|
||||||
if (!teamId) {
|
|
||||||
throw new AppError({ message: "No team ID in request", service: SERVICE_NAME, method: "deleteChecksByTeamId", status: 400 });
|
|
||||||
}
|
|
||||||
|
|
||||||
const deletedCount = await this.checksRepository.deleteByTeamId(teamId);
|
const deletedCount = await this.checksRepository.deleteByTeamId(teamId);
|
||||||
return deletedCount;
|
return deletedCount;
|
||||||
};
|
};
|
||||||
|
|
||||||
updateChecksTTL = async ({ teamId, ttl }: { teamId: string; ttl: string }) => {
|
deleteOlderThan = async (date: Date) => {
|
||||||
throw new AppError({ message: "Not implemented", service: SERVICE_NAME, method: "updateChecksTTL", status: 500, details: { teamId, ttl } });
|
const deletedCount = await this.checksRepository.deleteOlderThan(date);
|
||||||
|
return deletedCount;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -18,9 +18,7 @@ import type {
|
|||||||
IMonitorStatsRepository,
|
IMonitorStatsRepository,
|
||||||
IStatusPagesRepository,
|
IStatusPagesRepository,
|
||||||
} from "@/repositories/index.js";
|
} from "@/repositories/index.js";
|
||||||
import fs from "fs";
|
import demoMonitorsData from "@/utils/demoMonitors.json" with { type: "json" };
|
||||||
import { fileURLToPath } from "url";
|
|
||||||
import path from "path";
|
|
||||||
import { AppError } from "@/utils/AppError.js";
|
import { AppError } from "@/utils/AppError.js";
|
||||||
import { ISuperSimpleQueue } from "../infrastructure/SuperSimpleQueue/SuperSimpleQueue.js";
|
import { ISuperSimpleQueue } from "../infrastructure/SuperSimpleQueue/SuperSimpleQueue.js";
|
||||||
|
|
||||||
@@ -177,23 +175,17 @@ export class MonitorService implements IMonitorService {
|
|||||||
};
|
};
|
||||||
|
|
||||||
addDemoMonitors = async ({ userId, teamId }: { userId: string; teamId: string }): Promise<any[]> => {
|
addDemoMonitors = async ({ userId, teamId }: { userId: string; teamId: string }): Promise<any[]> => {
|
||||||
const __filename = fileURLToPath(import.meta.url);
|
const demoData = demoMonitorsData;
|
||||||
const __dirname = path.dirname(__filename);
|
const monitors = demoData.map((monitor) => ({
|
||||||
const demoMonitorsPath = path.resolve(__dirname, "../../utils/demoMonitors.json");
|
userId,
|
||||||
|
teamId,
|
||||||
const demoData = JSON.parse(fs.readFileSync(demoMonitorsPath, "utf8"));
|
name: monitor.name,
|
||||||
const monitors: Monitor[] = demoData.map((monitor: Monitor) => {
|
description: monitor.name,
|
||||||
return {
|
type: "http" as const,
|
||||||
userId,
|
url: monitor.url,
|
||||||
teamId,
|
interval: 60000,
|
||||||
name: monitor.name,
|
}));
|
||||||
description: monitor.name,
|
const demoMonitors = await this.monitorsRepository.createMonitors(monitors as unknown as Monitor[]);
|
||||||
type: "http",
|
|
||||||
url: monitor.url,
|
|
||||||
interval: 60000,
|
|
||||||
};
|
|
||||||
});
|
|
||||||
const demoMonitors = await this.monitorsRepository.createMonitors(monitors);
|
|
||||||
|
|
||||||
await Promise.all(demoMonitors.map((monitor) => this.jobQueue.addJob(monitor.id, monitor)));
|
await Promise.all(demoMonitors.map((monitor) => this.jobQueue.addJob(monitor.id, monitor)));
|
||||||
return demoMonitors;
|
return demoMonitors;
|
||||||
|
|||||||
@@ -12,24 +12,31 @@ import bcrypt from "bcryptjs";
|
|||||||
import { AppError } from "@/utils/AppError.js";
|
import { AppError } from "@/utils/AppError.js";
|
||||||
import { ISuperSimpleQueue } from "@/service/infrastructure/SuperSimpleQueue/SuperSimpleQueue.js";
|
import { ISuperSimpleQueue } from "@/service/infrastructure/SuperSimpleQueue/SuperSimpleQueue.js";
|
||||||
import { IEmailService } from "@/service/infrastructure/emailService.js";
|
import { IEmailService } from "@/service/infrastructure/emailService.js";
|
||||||
import { ISettingsService } from "@/service/system/settingsService.js";
|
import { EnvConfig, ISettingsService } from "@/service/system/settingsService.js";
|
||||||
import { ILogger } from "@/utils/logger.js";
|
import { ILogger } from "@/utils/logger.js";
|
||||||
import jwt from "jsonwebtoken";
|
import jwt from "jsonwebtoken";
|
||||||
|
import crypto from "crypto";
|
||||||
|
type CryptoType = typeof crypto;
|
||||||
type JwtType = typeof jwt;
|
type JwtType = typeof jwt;
|
||||||
const SERVICE_NAME = "userService";
|
const SERVICE_NAME = "userService";
|
||||||
|
|
||||||
export interface IUserService {
|
export interface IUserService {
|
||||||
issueToken(payload: Partial<User>, appSettings: { jwtTTL?: string; jwtSecret?: string }): string;
|
issueToken(payload: Partial<User>, appSettings: EnvConfig): string;
|
||||||
registerUser(user: Partial<User>, inviteToken: string, file: unknown): Promise<{ user: User; token: string }>;
|
registerUser(user: Partial<User>, inviteToken: string, file: Express.Multer.File | null): Promise<{ user: User; token: string }>;
|
||||||
createUser(userData: Partial<User>, teamId: string, actorRoles: UserRole[], file: unknown): Promise<User>;
|
createUser(userData: Partial<User>, teamId: string, actorRoles: UserRole[], file: Express.Multer.File | null): Promise<User>;
|
||||||
loginUser(email: string, password: string): Promise<{ user: User; token: string }>;
|
loginUser(email: string, password: string): Promise<{ user: User; token: string }>;
|
||||||
editUser(updates: Partial<User & { newPassword?: string }>, file: unknown, currentUser: User): Promise<User>;
|
editUser(
|
||||||
|
updates: Partial<User & { newPassword?: string }>,
|
||||||
|
file: Express.Multer.File | null,
|
||||||
|
currentUserId: string,
|
||||||
|
currentUserEmail: string
|
||||||
|
): Promise<User>;
|
||||||
checkSuperadminExists(): Promise<boolean>;
|
checkSuperadminExists(): Promise<boolean>;
|
||||||
requestRecovery(email: string): Promise<string | false | undefined>;
|
requestRecovery(email: string): Promise<string | false | undefined>;
|
||||||
validateRecovery(recoveryToken: string): Promise<void>;
|
validateRecovery(recoveryToken: string): Promise<void>;
|
||||||
resetPassword(password: string, recoveryToken: string): Promise<{ user: User; token: string }>;
|
resetPassword(password: string, recoveryToken: string): Promise<{ user: User; token: string }>;
|
||||||
deleteUser(user: User): Promise<void>;
|
deleteUser(params: { userId: string; teamId: string; roles: UserRole[] }): Promise<void>;
|
||||||
deleteUserById(actor: User, targetUserId: string): Promise<void>;
|
deleteUserById(params: { actorId: string; actorTeamId: string; actorRoles: UserRole[]; targetUserId: string }): Promise<void>;
|
||||||
getAllUsers(): Promise<User[]>;
|
getAllUsers(): Promise<User[]>;
|
||||||
getUserById(roles: UserRole[], userId: string): Promise<User>;
|
getUserById(roles: UserRole[], userId: string): Promise<User>;
|
||||||
editUserById(userId: string, patch: Partial<User>): Promise<void>;
|
editUserById(userId: string, patch: Partial<User>): Promise<void>;
|
||||||
@@ -49,7 +56,7 @@ export class UserService implements IUserService {
|
|||||||
private logger: ILogger;
|
private logger: ILogger;
|
||||||
private jwt: JwtType;
|
private jwt: JwtType;
|
||||||
private jobQueue: ISuperSimpleQueue;
|
private jobQueue: ISuperSimpleQueue;
|
||||||
private crypto: any;
|
private crypto: CryptoType;
|
||||||
private monitorsRepository: IMonitorsRepository;
|
private monitorsRepository: IMonitorsRepository;
|
||||||
private usersRepository: IUsersRepository;
|
private usersRepository: IUsersRepository;
|
||||||
private invitesRepository: IInvitesRepository;
|
private invitesRepository: IInvitesRepository;
|
||||||
@@ -71,7 +78,7 @@ export class UserService implements IUserService {
|
|||||||
settingsRepository,
|
settingsRepository,
|
||||||
teamsRepository,
|
teamsRepository,
|
||||||
}: {
|
}: {
|
||||||
crypto: any;
|
crypto: CryptoType;
|
||||||
emailService: IEmailService;
|
emailService: IEmailService;
|
||||||
settingsService: ISettingsService;
|
settingsService: ISettingsService;
|
||||||
logger: ILogger;
|
logger: ILogger;
|
||||||
@@ -102,14 +109,14 @@ export class UserService implements IUserService {
|
|||||||
return UserService.SERVICE_NAME;
|
return UserService.SERVICE_NAME;
|
||||||
}
|
}
|
||||||
|
|
||||||
issueToken = (payload: any, appSettings: any) => {
|
issueToken = (payload: Partial<User>, appSettings: EnvConfig) => {
|
||||||
const tokenTTL = appSettings?.jwtTTL ?? "2h";
|
const tokenTTL = appSettings?.jwtTTL ?? "2h";
|
||||||
const tokenSecret = appSettings?.jwtSecret;
|
const tokenSecret = appSettings?.jwtSecret;
|
||||||
const payloadData = payload;
|
const payloadData = payload;
|
||||||
return this.jwt.sign(payloadData, tokenSecret, { expiresIn: tokenTTL });
|
return this.jwt.sign(payloadData, tokenSecret, { expiresIn: tokenTTL });
|
||||||
};
|
};
|
||||||
|
|
||||||
registerUser = async (user: Partial<User>, inviteToken: string, file: any) => {
|
registerUser = async (user: Partial<User>, inviteToken: string, file: Express.Multer.File | null) => {
|
||||||
// Create a new user
|
// Create a new user
|
||||||
// If superAdmin exists, a token should be attached to all further register requests
|
// If superAdmin exists, a token should be attached to all further register requests
|
||||||
const superAdminExists = await this.usersRepository.findSuperAdmin();
|
const superAdminExists = await this.usersRepository.findSuperAdmin();
|
||||||
@@ -179,7 +186,7 @@ export class UserService implements IUserService {
|
|||||||
return { user: newUser, token };
|
return { user: newUser, token };
|
||||||
};
|
};
|
||||||
|
|
||||||
createUser = async (userData: Partial<User>, teamId: string, actorRoles: UserRole[], file: any) => {
|
createUser = async (userData: Partial<User>, teamId: string, actorRoles: UserRole[], file: Express.Multer.File | null) => {
|
||||||
// Validate that the creator can assign the requested roles
|
// Validate that the creator can assign the requested roles
|
||||||
const targetRoles = userData.role ?? [];
|
const targetRoles = userData.role ?? [];
|
||||||
for (const targetRole of targetRoles) {
|
for (const targetRole of targetRoles) {
|
||||||
@@ -239,14 +246,19 @@ export class UserService implements IUserService {
|
|||||||
return { user: userWithoutPassword, token };
|
return { user: userWithoutPassword, token };
|
||||||
};
|
};
|
||||||
|
|
||||||
editUser = async (updates: Partial<User & { newPassword?: string }>, file: any, currentUser: any) => {
|
editUser = async (
|
||||||
|
updates: Partial<User & { newPassword?: string }>,
|
||||||
|
file: Express.Multer.File | null,
|
||||||
|
currentUserId: string,
|
||||||
|
currentUserEmail: string
|
||||||
|
) => {
|
||||||
// Change Password check
|
// Change Password check
|
||||||
if (updates?.password && updates?.newPassword) {
|
if (updates?.password && updates?.newPassword) {
|
||||||
// Get user's email
|
// Get user's email
|
||||||
// Add user email to body for DB operation
|
// Add user email to body for DB operation
|
||||||
updates.email = currentUser.email;
|
updates.email = currentUserEmail;
|
||||||
// Get user
|
// Get user
|
||||||
const user = await this.usersRepository.findByEmail(currentUser.email);
|
const user = await this.usersRepository.findByEmail(currentUserEmail);
|
||||||
// Compare passwords
|
// Compare passwords
|
||||||
const match = await bcrypt.compare(updates?.password, user.password);
|
const match = await bcrypt.compare(updates?.password, user.password);
|
||||||
// If not a match, throw a 403
|
// If not a match, throw a 403
|
||||||
@@ -259,7 +271,7 @@ export class UserService implements IUserService {
|
|||||||
delete updates.newPassword;
|
delete updates.newPassword;
|
||||||
}
|
}
|
||||||
|
|
||||||
return await this.usersRepository.updateById(currentUser.id, updates, file);
|
return await this.usersRepository.updateById(currentUserId, updates, file);
|
||||||
};
|
};
|
||||||
|
|
||||||
checkSuperadminExists = async () => {
|
checkSuperadminExists = async () => {
|
||||||
@@ -273,8 +285,8 @@ export class UserService implements IUserService {
|
|||||||
await this.recoveryTokensRepository.deleteManyByEmail(email);
|
await this.recoveryTokensRepository.deleteManyByEmail(email);
|
||||||
const recoveryToken = await this.recoveryTokensRepository.create(email);
|
const recoveryToken = await this.recoveryTokensRepository.create(email);
|
||||||
const name = user.firstName;
|
const name = user.firstName;
|
||||||
const { clientHost } = this.settingsService.getSettings();
|
const settings = this.settingsService.getSettings();
|
||||||
const url = `${clientHost}/set-new-password/${recoveryToken.token}`;
|
const url = `${settings.clientHost!}/set-new-password/${recoveryToken.token}`;
|
||||||
|
|
||||||
const html = await this.emailService.buildEmail("passwordResetTemplate", {
|
const html = await this.emailService.buildEmail("passwordResetTemplate", {
|
||||||
name,
|
name,
|
||||||
@@ -319,24 +331,7 @@ export class UserService implements IUserService {
|
|||||||
return { user: existingUser, token };
|
return { user: existingUser, token };
|
||||||
};
|
};
|
||||||
|
|
||||||
deleteUser = async (user: User) => {
|
deleteUser = async ({ userId, teamId, roles }: { userId: string; teamId: string; roles: UserRole[] }) => {
|
||||||
const email = user?.email;
|
|
||||||
if (!email) {
|
|
||||||
throw new AppError({ message: "No email in request", service: SERVICE_NAME, method: "deleteUser", status: 400 });
|
|
||||||
}
|
|
||||||
|
|
||||||
const teamId = user?.teamId;
|
|
||||||
const userId = user?.id;
|
|
||||||
|
|
||||||
if (!teamId) {
|
|
||||||
throw new AppError({ message: "No team ID in request", service: SERVICE_NAME, method: "deleteUser", status: 400 });
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!userId) {
|
|
||||||
throw new AppError({ message: "No user ID in request", service: SERVICE_NAME, method: "deleteUser", status: 400 });
|
|
||||||
}
|
|
||||||
|
|
||||||
const roles = user?.role;
|
|
||||||
if (roles.includes("demo")) {
|
if (roles.includes("demo")) {
|
||||||
throw new AppError({ message: "Demo user cannot be deleted", service: SERVICE_NAME, method: "deleteUser", status: 400 });
|
throw new AppError({ message: "Demo user cannot be deleted", service: SERVICE_NAME, method: "deleteUser", status: 400 });
|
||||||
}
|
}
|
||||||
@@ -349,7 +344,7 @@ export class UserService implements IUserService {
|
|||||||
if (res && res.length > 0) {
|
if (res && res.length > 0) {
|
||||||
await Promise.all(
|
await Promise.all(
|
||||||
res.map(async (monitor) => {
|
res.map(async (monitor) => {
|
||||||
await this.jobQueue.deleteJob(monitor.id);
|
await this.jobQueue.deleteJob(monitor);
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -358,14 +353,24 @@ export class UserService implements IUserService {
|
|||||||
await this.usersRepository.deleteById(userId);
|
await this.usersRepository.deleteById(userId);
|
||||||
};
|
};
|
||||||
|
|
||||||
deleteUserById = async (actor: User, targetUserId: string) => {
|
deleteUserById = async ({
|
||||||
if (actor.id === targetUserId) {
|
actorId,
|
||||||
|
actorRoles,
|
||||||
|
actorTeamId,
|
||||||
|
targetUserId,
|
||||||
|
}: {
|
||||||
|
actorId: string;
|
||||||
|
actorTeamId: string;
|
||||||
|
actorRoles: UserRole[];
|
||||||
|
targetUserId: string;
|
||||||
|
}) => {
|
||||||
|
if (actorId === targetUserId) {
|
||||||
throw new AppError({ message: "Cannot delete your own account from here", service: SERVICE_NAME, method: "deleteUserById", status: 400 });
|
throw new AppError({ message: "Cannot delete your own account from here", service: SERVICE_NAME, method: "deleteUserById", status: 400 });
|
||||||
}
|
}
|
||||||
|
|
||||||
const targetUser = await this.usersRepository.findById(targetUserId);
|
const targetUser = await this.usersRepository.findById(targetUserId);
|
||||||
|
|
||||||
if (targetUser.teamId !== actor.teamId) {
|
if (targetUser.teamId !== actorTeamId) {
|
||||||
throw new AppError({ message: "User is not on your team", service: SERVICE_NAME, method: "deleteUserById", status: 403 });
|
throw new AppError({ message: "User is not on your team", service: SERVICE_NAME, method: "deleteUserById", status: 403 });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -373,7 +378,6 @@ export class UserService implements IUserService {
|
|||||||
throw new AppError({ message: "Demo user cannot be deleted", service: SERVICE_NAME, method: "deleteUserById", status: 400 });
|
throw new AppError({ message: "Demo user cannot be deleted", service: SERVICE_NAME, method: "deleteUserById", status: 400 });
|
||||||
}
|
}
|
||||||
|
|
||||||
const actorRoles = actor.role;
|
|
||||||
const targetRoles = targetUser.role;
|
const targetRoles = targetUser.role;
|
||||||
|
|
||||||
// Check actor can manage all of target's roles
|
// Check actor can manage all of target's roles
|
||||||
@@ -392,7 +396,7 @@ export class UserService implements IUserService {
|
|||||||
await this.usersRepository.deleteById(targetUserId);
|
await this.usersRepository.deleteById(targetUserId);
|
||||||
|
|
||||||
this.logger.info({
|
this.logger.info({
|
||||||
message: `User ${targetUserId} deleted by ${actor.id}`,
|
message: `User ${targetUserId} deleted by ${actorId}`,
|
||||||
service: SERVICE_NAME,
|
service: SERVICE_NAME,
|
||||||
method: "deleteUserById",
|
method: "deleteUserById",
|
||||||
});
|
});
|
||||||
@@ -402,7 +406,7 @@ export class UserService implements IUserService {
|
|||||||
return await this.usersRepository.findAll();
|
return await this.usersRepository.findAll();
|
||||||
};
|
};
|
||||||
|
|
||||||
getUserById = async (roles: any, userId: any) => {
|
getUserById = async (roles: UserRole[], userId: string) => {
|
||||||
if (!roles.includes("superadmin") && !roles.includes("admin")) {
|
if (!roles.includes("superadmin") && !roles.includes("admin")) {
|
||||||
throw new AppError({ message: "Insufficient permissions", service: SERVICE_NAME, status: 403 });
|
throw new AppError({ message: "Insufficient permissions", service: SERVICE_NAME, status: 403 });
|
||||||
}
|
}
|
||||||
@@ -411,11 +415,11 @@ export class UserService implements IUserService {
|
|||||||
return user;
|
return user;
|
||||||
};
|
};
|
||||||
|
|
||||||
editUserById = async (userId: any, patch: Partial<User>) => {
|
editUserById = async (userId: string, patch: Partial<User>) => {
|
||||||
await this.usersRepository.updateById(userId, patch, null);
|
await this.usersRepository.updateById(userId, patch, null);
|
||||||
};
|
};
|
||||||
|
|
||||||
setPasswordByUserId = async (userId: any, password: string) => {
|
setPasswordByUserId = async (userId: string, password: string) => {
|
||||||
const hashedPassword = this.hashPassword(password);
|
const hashedPassword = this.hashPassword(password);
|
||||||
const updatedUser = await this.usersRepository.updateById(userId, { password: hashedPassword }, null);
|
const updatedUser = await this.usersRepository.updateById(userId, { password: hashedPassword }, null);
|
||||||
return updatedUser;
|
return updatedUser;
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ export * from "@/service/infrastructure/notificationProviders/INotificationProvi
|
|||||||
export * from "@/service/infrastructure/notificationProviders/matrix.js";
|
export * from "@/service/infrastructure/notificationProviders/matrix.js";
|
||||||
export * from "@/service/infrastructure/notificationProviders/pagerduty.js";
|
export * from "@/service/infrastructure/notificationProviders/pagerduty.js";
|
||||||
export * from "@/service/infrastructure/notificationProviders/slack.js";
|
export * from "@/service/infrastructure/notificationProviders/slack.js";
|
||||||
|
export * from "@/service/infrastructure/notificationProviders/teams.js";
|
||||||
export * from "@/service/infrastructure/notificationProviders/webhook.js";
|
export * from "@/service/infrastructure/notificationProviders/webhook.js";
|
||||||
|
|
||||||
// System services
|
// System services
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { IMonitorsRepository } from "@/repositories/index.js";
|
|||||||
import { ILogger } from "@/utils/logger.js";
|
import { ILogger } from "@/utils/logger.js";
|
||||||
import Scheduler from "super-simple-scheduler";
|
import Scheduler from "super-simple-scheduler";
|
||||||
import { ISuperSimpleQueueHelper } from "@/service/infrastructure/SuperSimpleQueue/SuperSimpleQueueHelper.js";
|
import { ISuperSimpleQueueHelper } from "@/service/infrastructure/SuperSimpleQueue/SuperSimpleQueueHelper.js";
|
||||||
import { supportsGeoCheck } from "@/types/monitor.js";
|
import { Monitor, MonitorType, supportsGeoCheck } from "@/types/monitor.js";
|
||||||
const SERVICE_NAME = "JobQueue";
|
const SERVICE_NAME = "JobQueue";
|
||||||
|
|
||||||
type QueueJobFailure = {
|
type QueueJobFailure = {
|
||||||
@@ -42,11 +42,11 @@ type QueueJobSummary = {
|
|||||||
export interface ISuperSimpleQueue {
|
export interface ISuperSimpleQueue {
|
||||||
readonly serviceName: string;
|
readonly serviceName: string;
|
||||||
init(): Promise<boolean>;
|
init(): Promise<boolean>;
|
||||||
addJob(monitorId: string, monitor: any): Promise<void>;
|
addJob(monitorId: string, monitor: Monitor): Promise<void>;
|
||||||
deleteJob(monitor: any): Promise<void>;
|
deleteJob(monitor: Monitor): Promise<void>;
|
||||||
pauseJob(monitor: any): Promise<void>;
|
pauseJob(monitor: Monitor): Promise<void>;
|
||||||
resumeJob(monitor: any): Promise<void>;
|
resumeJob(monitor: Monitor): Promise<void>;
|
||||||
updateJob(monitor: any): Promise<void>;
|
updateJob(monitor: Monitor): Promise<void>;
|
||||||
shutdown(): Promise<void>;
|
shutdown(): Promise<void>;
|
||||||
getMetrics(): Promise<QueueMetrics>;
|
getMetrics(): Promise<QueueMetrics>;
|
||||||
getJobs(): Promise<QueueJobSummary[]>;
|
getJobs(): Promise<QueueJobSummary[]>;
|
||||||
@@ -89,9 +89,10 @@ export class SuperSimpleQueue implements ISuperSimpleQueue {
|
|||||||
try {
|
try {
|
||||||
this.scheduler.start();
|
this.scheduler.start();
|
||||||
|
|
||||||
this.scheduler.addTemplate("monitor-job", this.helper.getMonitorJob());
|
this.scheduler.addTemplate("monitor-job", this.helper.getHeartbeatJob());
|
||||||
this.scheduler.addTemplate("geo-check-job", this.helper.getGeoCheckJob());
|
this.scheduler.addTemplate("geo-check-job", this.helper.getHeartbeatGeoJob());
|
||||||
this.scheduler.addTemplate("cleanup-orphaned", this.helper.getCleanupOrphanedJob());
|
this.scheduler.addTemplate("cleanup-orphaned", this.helper.getCleanupOrphanedJob());
|
||||||
|
this.scheduler.addTemplate("cleanup-retention-job", this.helper.getCleanupRetentionJob());
|
||||||
const monitors = await this.monitorsRepository.findAll();
|
const monitors = await this.monitorsRepository.findAll();
|
||||||
if (!monitors) {
|
if (!monitors) {
|
||||||
return true;
|
return true;
|
||||||
@@ -104,20 +105,20 @@ export class SuperSimpleQueue implements ISuperSimpleQueue {
|
|||||||
}
|
}
|
||||||
|
|
||||||
this.scheduler.addJob({ id: "cleanup-orphaned", template: "cleanup-orphaned", active: true });
|
this.scheduler.addJob({ id: "cleanup-orphaned", template: "cleanup-orphaned", active: true });
|
||||||
|
this.scheduler.addJob({ id: "cleanup-retention", template: "cleanup-retention-job", active: true, repeat: 24 * 60 * 60 * 1000 });
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
} catch (error: any) {
|
} catch (error: unknown) {
|
||||||
this.logger.error({
|
this.logger.error({
|
||||||
message: "Failed to initialize SuperSimpleQueue",
|
message: `Failed to initialize SuperSimpleQueue: ${error instanceof Error ? error.message : String(error)}`,
|
||||||
service: SERVICE_NAME,
|
service: SERVICE_NAME,
|
||||||
method: "init",
|
method: "init",
|
||||||
details: error,
|
|
||||||
});
|
});
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
addJob = async (monitorId: string, monitor: any) => {
|
addJob = async (monitorId: string, monitor: Monitor) => {
|
||||||
this.scheduler.addJob({
|
this.scheduler.addJob({
|
||||||
id: monitorId,
|
id: monitorId,
|
||||||
template: "monitor-job",
|
template: "monitor-job",
|
||||||
@@ -143,12 +144,12 @@ export class SuperSimpleQueue implements ISuperSimpleQueue {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
deleteJob = async (monitor: any) => {
|
deleteJob = async (monitor: Monitor) => {
|
||||||
this.scheduler.removeJob(monitor.id);
|
this.scheduler.removeJob(monitor.id);
|
||||||
this.scheduler.removeJob(`${monitor.id}-geo`);
|
this.scheduler.removeJob(`${monitor.id}-geo`);
|
||||||
};
|
};
|
||||||
|
|
||||||
pauseJob = async (monitor: any) => {
|
pauseJob = async (monitor: Monitor) => {
|
||||||
const result = await this.scheduler.pauseJob(monitor.id);
|
const result = await this.scheduler.pauseJob(monitor.id);
|
||||||
if (result === false) {
|
if (result === false) {
|
||||||
throw new Error("Failed to pause monitor");
|
throw new Error("Failed to pause monitor");
|
||||||
@@ -161,7 +162,7 @@ export class SuperSimpleQueue implements ISuperSimpleQueue {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
resumeJob = async (monitor: any) => {
|
resumeJob = async (monitor: Monitor) => {
|
||||||
const result = await this.scheduler.resumeJob(monitor.id);
|
const result = await this.scheduler.resumeJob(monitor.id);
|
||||||
if (result === false) {
|
if (result === false) {
|
||||||
throw new Error("Failed to resume monitor");
|
throw new Error("Failed to resume monitor");
|
||||||
@@ -176,7 +177,7 @@ export class SuperSimpleQueue implements ISuperSimpleQueue {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
updateJob = async (monitor: any) => {
|
updateJob = async (monitor: Monitor) => {
|
||||||
this.scheduler.updateJob(monitor.id, { repeat: monitor.interval, data: monitor });
|
this.scheduler.updateJob(monitor.id, { repeat: monitor.interval, data: monitor });
|
||||||
|
|
||||||
// Handle geo check job lifecycle
|
// Handle geo check job lifecycle
|
||||||
@@ -244,8 +245,8 @@ export class SuperSimpleQueue implements ISuperSimpleQueue {
|
|||||||
failingJobs: 0,
|
failingJobs: 0,
|
||||||
jobsWithFailures: [] as Array<{
|
jobsWithFailures: [] as Array<{
|
||||||
monitorId: string | number;
|
monitorId: string | number;
|
||||||
monitorUrl: any;
|
monitorUrl: string;
|
||||||
monitorType: any;
|
monitorType: MonitorType;
|
||||||
failedAt: number | null;
|
failedAt: number | null;
|
||||||
failCount: number;
|
failCount: number;
|
||||||
failReason: string | null;
|
failReason: string | null;
|
||||||
|
|||||||
@@ -2,8 +2,16 @@ const SERVICE_NAME = "JobQueueHelper";
|
|||||||
import type { Monitor } from "@/types/monitor.js";
|
import type { Monitor } from "@/types/monitor.js";
|
||||||
import { supportsGeoCheck } from "@/types/monitor.js";
|
import { supportsGeoCheck } from "@/types/monitor.js";
|
||||||
import { AppError } from "@/utils/AppError.js";
|
import { AppError } from "@/utils/AppError.js";
|
||||||
import { INetworkService, INotificationsService, IStatusService, IncidentService, type IGeoChecksService } from "@/service/index.js";
|
import {
|
||||||
import type { StatusChangeResult } from "@/types/index.js";
|
ICheckService,
|
||||||
|
INetworkService,
|
||||||
|
INotificationsService,
|
||||||
|
ISettingsService,
|
||||||
|
IStatusService,
|
||||||
|
IncidentService,
|
||||||
|
type IGeoChecksService,
|
||||||
|
} from "@/service/index.js";
|
||||||
|
import { CHECK_TTL_SENTINEL, type MaintenanceWindow, type StatusChangeResult } from "@/types/index.js";
|
||||||
import {
|
import {
|
||||||
IMaintenanceWindowsRepository,
|
IMaintenanceWindowsRepository,
|
||||||
IMonitorsRepository,
|
IMonitorsRepository,
|
||||||
@@ -18,9 +26,10 @@ import { IBufferService } from "@/service/index.js";
|
|||||||
|
|
||||||
export interface ISuperSimpleQueueHelper {
|
export interface ISuperSimpleQueueHelper {
|
||||||
readonly serviceName: string;
|
readonly serviceName: string;
|
||||||
getMonitorJob(): (monitor: Monitor) => Promise<void>;
|
getHeartbeatJob(): (monitor: Monitor) => Promise<void>;
|
||||||
|
getHeartbeatGeoJob(): (monitor: Monitor) => Promise<void>;
|
||||||
getCleanupOrphanedJob(): () => Promise<void>;
|
getCleanupOrphanedJob(): () => Promise<void>;
|
||||||
getGeoCheckJob(): (monitor: Monitor) => Promise<void>;
|
getCleanupRetentionJob(): () => Promise<void>;
|
||||||
isInMaintenanceWindow(monitorId: string, teamId: string): Promise<boolean>;
|
isInMaintenanceWindow(monitorId: string, teamId: string): Promise<boolean>;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -41,11 +50,12 @@ export interface MonitorActionDecision {
|
|||||||
export class SuperSimpleQueueHelper implements ISuperSimpleQueueHelper {
|
export class SuperSimpleQueueHelper implements ISuperSimpleQueueHelper {
|
||||||
static SERVICE_NAME = SERVICE_NAME;
|
static SERVICE_NAME = SERVICE_NAME;
|
||||||
|
|
||||||
private logger: any;
|
private logger: ILogger;
|
||||||
private networkService: INetworkService;
|
private networkService: INetworkService;
|
||||||
private statusService: IStatusService;
|
private statusService: IStatusService;
|
||||||
private notificationsService: INotificationsService;
|
private notificationsService: INotificationsService;
|
||||||
private checkService: any;
|
private checkService: ICheckService;
|
||||||
|
private settingsService: ISettingsService;
|
||||||
private buffer: IBufferService;
|
private buffer: IBufferService;
|
||||||
private incidentService: IncidentService;
|
private incidentService: IncidentService;
|
||||||
private maintenanceWindowsRepository: IMaintenanceWindowsRepository;
|
private maintenanceWindowsRepository: IMaintenanceWindowsRepository;
|
||||||
@@ -62,7 +72,8 @@ export class SuperSimpleQueueHelper implements ISuperSimpleQueueHelper {
|
|||||||
networkService: INetworkService,
|
networkService: INetworkService,
|
||||||
statusService: IStatusService,
|
statusService: IStatusService,
|
||||||
notificationsService: INotificationsService,
|
notificationsService: INotificationsService,
|
||||||
checkService: any,
|
checkService: ICheckService,
|
||||||
|
settingsService: ISettingsService,
|
||||||
buffer: IBufferService,
|
buffer: IBufferService,
|
||||||
incidentService: IncidentService,
|
incidentService: IncidentService,
|
||||||
maintenanceWindowsRepository: IMaintenanceWindowsRepository,
|
maintenanceWindowsRepository: IMaintenanceWindowsRepository,
|
||||||
@@ -78,6 +89,7 @@ export class SuperSimpleQueueHelper implements ISuperSimpleQueueHelper {
|
|||||||
this.networkService = networkService;
|
this.networkService = networkService;
|
||||||
this.statusService = statusService;
|
this.statusService = statusService;
|
||||||
this.checkService = checkService;
|
this.checkService = checkService;
|
||||||
|
this.settingsService = settingsService;
|
||||||
this.buffer = buffer;
|
this.buffer = buffer;
|
||||||
this.notificationsService = notificationsService;
|
this.notificationsService = notificationsService;
|
||||||
this.incidentService = incidentService;
|
this.incidentService = incidentService;
|
||||||
@@ -95,7 +107,7 @@ export class SuperSimpleQueueHelper implements ISuperSimpleQueueHelper {
|
|||||||
return SuperSimpleQueueHelper.SERVICE_NAME;
|
return SuperSimpleQueueHelper.SERVICE_NAME;
|
||||||
}
|
}
|
||||||
|
|
||||||
getMonitorJob = () => {
|
getHeartbeatJob = () => {
|
||||||
return async (monitor: Monitor) => {
|
return async (monitor: Monitor) => {
|
||||||
try {
|
try {
|
||||||
const monitorId = monitor.id;
|
const monitorId = monitor.id;
|
||||||
@@ -126,7 +138,7 @@ export class SuperSimpleQueueHelper implements ISuperSimpleQueueHelper {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Step 3. Build check
|
// Step 3. Build check
|
||||||
const check = await this.checkService.buildCheck(status);
|
const check = this.checkService.buildCheck(status);
|
||||||
if (!check) {
|
if (!check) {
|
||||||
this.logger.warn({
|
this.logger.warn({
|
||||||
message: `No check could be built for monitor ${monitorId}`,
|
message: `No check could be built for monitor ${monitorId}`,
|
||||||
@@ -146,33 +158,31 @@ export class SuperSimpleQueueHelper implements ISuperSimpleQueueHelper {
|
|||||||
|
|
||||||
// Step 6. Handle notifications (best effort, continue even in event of failure, don't wait)
|
// Step 6. Handle notifications (best effort, continue even in event of failure, don't wait)
|
||||||
if (decision.shouldSendNotification) {
|
if (decision.shouldSendNotification) {
|
||||||
this.notificationsService.handleNotifications(statusChangeResult.monitor, status, decision).catch((error: any) => {
|
this.notificationsService.handleNotifications(statusChangeResult.monitor, status, decision).catch((error: unknown) => {
|
||||||
this.logger.error({
|
this.logger.error({
|
||||||
message: error.message,
|
message: `Error sending notifications for job ${statusChangeResult.monitor.id}: ${error instanceof Error ? error.message : "Unknown error"}`,
|
||||||
service: SERVICE_NAME,
|
service: SERVICE_NAME,
|
||||||
method: "getMonitorJob",
|
method: "getMonitorJob",
|
||||||
details: `Error sending notifications for job ${statusChangeResult.monitor.id}: ${error.message}`,
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
stack: error.stack,
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Step 7. Handle incidents (best effort, don't wait)
|
// Step 7. Handle incidents (best effort, don't wait)
|
||||||
this.incidentService.handleIncident(statusChangeResult.monitor, statusChangeResult.code, decision, status).catch((error: any) => {
|
this.incidentService.handleIncident(statusChangeResult.monitor, statusChangeResult.code, decision, status).catch((error: unknown) => {
|
||||||
this.logger.warn({
|
this.logger.warn({
|
||||||
message: error.message,
|
message: `Error handling incident for job ${monitor.id}: ${error instanceof Error ? error.message : "Unknown error"}`,
|
||||||
service: SERVICE_NAME,
|
service: SERVICE_NAME,
|
||||||
method: "getMonitorJob",
|
method: "getMonitorJob",
|
||||||
details: `Error handling incident for job ${monitor.id}: ${error.message}`,
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
stack: error.stack,
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
} catch (error: any) {
|
} catch (error: unknown) {
|
||||||
this.logger.warn({
|
this.logger.warn({
|
||||||
message: error.message,
|
message: error instanceof Error ? error.message : "Unknown error",
|
||||||
service: error.service || SERVICE_NAME,
|
service: SERVICE_NAME,
|
||||||
method: error.method || "getMonitorJob",
|
method: "getMonitorJob",
|
||||||
stack: error.stack,
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
});
|
});
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
@@ -258,19 +268,19 @@ export class SuperSimpleQueueHelper implements ISuperSimpleQueueHelper {
|
|||||||
service: SERVICE_NAME,
|
service: SERVICE_NAME,
|
||||||
method: "getCleanupOrphanedJob",
|
method: "getCleanupOrphanedJob",
|
||||||
});
|
});
|
||||||
} catch (error: any) {
|
} catch (error: unknown) {
|
||||||
this.logger.warn({
|
this.logger.warn({
|
||||||
message: error.message,
|
message: error instanceof Error ? error.message : "Unknown error",
|
||||||
service: SERVICE_NAME,
|
service: SERVICE_NAME,
|
||||||
method: "getCleanupOrphanedJob",
|
method: "getCleanupOrphanedJob",
|
||||||
stack: error.stack,
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
});
|
});
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
getGeoCheckJob = () => {
|
getHeartbeatGeoJob = () => {
|
||||||
return async (monitor: Monitor) => {
|
return async (monitor: Monitor) => {
|
||||||
try {
|
try {
|
||||||
const monitorId = monitor.id;
|
const monitorId = monitor.id;
|
||||||
@@ -278,7 +288,7 @@ export class SuperSimpleQueueHelper implements ISuperSimpleQueueHelper {
|
|||||||
|
|
||||||
// Step 1: Validate monitor eligibility
|
// Step 1: Validate monitor eligibility
|
||||||
if (!monitorId) {
|
if (!monitorId) {
|
||||||
throw new AppError({ message: "No monitor id", service: SERVICE_NAME, method: "getGeoCheckJob" });
|
throw new AppError({ message: "No monitor id", service: SERVICE_NAME, method: "getHeartbeatGeoJob" });
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!monitor.geoCheckEnabled) {
|
if (!monitor.geoCheckEnabled) {
|
||||||
@@ -288,7 +298,7 @@ export class SuperSimpleQueueHelper implements ISuperSimpleQueueHelper {
|
|||||||
this.logger.debug({
|
this.logger.debug({
|
||||||
message: `Monitor ${monitorId} type does not support geo checks, skipping`,
|
message: `Monitor ${monitorId} type does not support geo checks, skipping`,
|
||||||
service: SERVICE_NAME,
|
service: SERVICE_NAME,
|
||||||
method: "getGeoCheckJob",
|
method: "getHeartbeatGeoJob",
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -297,7 +307,7 @@ export class SuperSimpleQueueHelper implements ISuperSimpleQueueHelper {
|
|||||||
this.logger.warn({
|
this.logger.warn({
|
||||||
message: `No geo check locations configured for monitor ${monitorId}`,
|
message: `No geo check locations configured for monitor ${monitorId}`,
|
||||||
service: SERVICE_NAME,
|
service: SERVICE_NAME,
|
||||||
method: "getGeoCheckJob",
|
method: "getHeartbeatGeoJob",
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -308,7 +318,7 @@ export class SuperSimpleQueueHelper implements ISuperSimpleQueueHelper {
|
|||||||
this.logger.debug({
|
this.logger.debug({
|
||||||
message: `Monitor ${monitorId} is in maintenance window, skipping geo check`,
|
message: `Monitor ${monitorId} is in maintenance window, skipping geo check`,
|
||||||
service: SERVICE_NAME,
|
service: SERVICE_NAME,
|
||||||
method: "getGeoCheckJob",
|
method: "getHeartbeatGeoJob",
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -319,7 +329,7 @@ export class SuperSimpleQueueHelper implements ISuperSimpleQueueHelper {
|
|||||||
this.logger.warn({
|
this.logger.warn({
|
||||||
message: `No geo check could be built for monitor ${monitorId}`,
|
message: `No geo check could be built for monitor ${monitorId}`,
|
||||||
service: SERVICE_NAME,
|
service: SERVICE_NAME,
|
||||||
method: "getGeoCheckJob",
|
method: "getHeartbeatGeoJob",
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -330,14 +340,14 @@ export class SuperSimpleQueueHelper implements ISuperSimpleQueueHelper {
|
|||||||
this.logger.debug({
|
this.logger.debug({
|
||||||
message: `Geo check job executed for monitor ${monitorId}`,
|
message: `Geo check job executed for monitor ${monitorId}`,
|
||||||
service: SERVICE_NAME,
|
service: SERVICE_NAME,
|
||||||
method: "getGeoCheckJob",
|
method: "getHeartbeatGeoJob",
|
||||||
});
|
});
|
||||||
} catch (error: any) {
|
} catch (error: unknown) {
|
||||||
this.logger.error({
|
this.logger.error({
|
||||||
message: error.message,
|
message: error instanceof Error ? error.message : "Unknown error",
|
||||||
service: SERVICE_NAME,
|
service: SERVICE_NAME,
|
||||||
method: "getGeoCheckJob",
|
method: "getHeartbeatGeoJob",
|
||||||
stack: error.stack,
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
});
|
});
|
||||||
// Don't throw - geo check failures shouldn't crash the job scheduler
|
// Don't throw - geo check failures shouldn't crash the job scheduler
|
||||||
}
|
}
|
||||||
@@ -347,7 +357,7 @@ export class SuperSimpleQueueHelper implements ISuperSimpleQueueHelper {
|
|||||||
async isInMaintenanceWindow(monitorId: string, teamId: string) {
|
async isInMaintenanceWindow(monitorId: string, teamId: string) {
|
||||||
const maintenanceWindows = await this.maintenanceWindowsRepository.findByMonitorId(monitorId, teamId);
|
const maintenanceWindows = await this.maintenanceWindowsRepository.findByMonitorId(monitorId, teamId);
|
||||||
// Check for active maintenance window:
|
// Check for active maintenance window:
|
||||||
const maintenanceWindowIsActive = maintenanceWindows.reduce((acc: any, window: any) => {
|
const maintenanceWindowIsActive = maintenanceWindows.reduce((acc: boolean, window: MaintenanceWindow) => {
|
||||||
if (window.active) {
|
if (window.active) {
|
||||||
const start = new Date(window.start);
|
const start = new Date(window.start);
|
||||||
const end = new Date(window.end);
|
const end = new Date(window.end);
|
||||||
@@ -374,6 +384,40 @@ export class SuperSimpleQueueHelper implements ISuperSimpleQueueHelper {
|
|||||||
return maintenanceWindowIsActive;
|
return maintenanceWindowIsActive;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
getCleanupRetentionJob = () => {
|
||||||
|
return async () => {
|
||||||
|
try {
|
||||||
|
const settings = await this.settingsService.getDBSettings();
|
||||||
|
|
||||||
|
const checkTTL = settings.checkTTL; // Check TTL is in DAYS, not MS
|
||||||
|
|
||||||
|
if (checkTTL === CHECK_TTL_SENTINEL) {
|
||||||
|
this.logger.info({
|
||||||
|
message: `Check TTL is set to unlimited, skipping cleanup`,
|
||||||
|
service: SERVICE_NAME,
|
||||||
|
method: "getCleanupRetentionJob",
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const checkTTLInMs = checkTTL * 24 * 60 * 60 * 1000;
|
||||||
|
const cutoffDate = new Date(Date.now() - checkTTLInMs);
|
||||||
|
const deleteCount = await this.checkService.deleteOlderThan(cutoffDate);
|
||||||
|
this.logger.info({
|
||||||
|
message: `Deleted ${deleteCount} checks older than ${cutoffDate.toISOString()}`,
|
||||||
|
service: SERVICE_NAME,
|
||||||
|
method: "getCleanupRetentionJob",
|
||||||
|
});
|
||||||
|
} catch (error: unknown) {
|
||||||
|
this.logger.error({
|
||||||
|
message: error instanceof Error ? error.message : "Unknown error",
|
||||||
|
service: SERVICE_NAME,
|
||||||
|
method: "getCleanupRetentionJob",
|
||||||
|
stack: error instanceof Error ? error.stack : undefined,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
private evaluateMonitorAction(statusChangeResult: StatusChangeResult): MonitorActionDecision {
|
private evaluateMonitorAction(statusChangeResult: StatusChangeResult): MonitorActionDecision {
|
||||||
const { monitor, statusChanged, prevStatus } = statusChangeResult;
|
const { monitor, statusChanged, prevStatus } = statusChangeResult;
|
||||||
|
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ export class HttpProvider implements IStatusProvider<HttpStatusPayload> {
|
|||||||
private got: Got,
|
private got: Got,
|
||||||
private advancedMatcher: AdvancedMatcher
|
private advancedMatcher: AdvancedMatcher
|
||||||
) {
|
) {
|
||||||
const cacheable = new CacheableLookup();
|
const cacheable = new CacheableLookup({ maxTtl: 300, errorTtl: 30 });
|
||||||
this.got = got.extend({
|
this.got = got.extend({
|
||||||
dnsCache: cacheable,
|
dnsCache: cacheable,
|
||||||
timeout: {
|
timeout: {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import type { Monitor, MonitorStatusResponse } from "@/types/index.js";
|
import type { Monitor, MonitorStatusResponse, MonitorPayloadMap, MonitorType } from "@/types/index.js";
|
||||||
import type { AxiosStatic } from "axios";
|
import type { AxiosStatic } from "axios";
|
||||||
import { AppError } from "@/utils/AppError.js";
|
import { AppError } from "@/utils/AppError.js";
|
||||||
import { NETWORK_ERROR } from "@/service/infrastructure/network/utils.js";
|
import { NETWORK_ERROR } from "@/service/infrastructure/network/utils.js";
|
||||||
@@ -8,7 +8,7 @@ const SERVICE_NAME = "NetworkService";
|
|||||||
|
|
||||||
export interface INetworkService {
|
export interface INetworkService {
|
||||||
readonly serviceName: string;
|
readonly serviceName: string;
|
||||||
requestStatus(monitor: Monitor): Promise<MonitorStatusResponse<unknown>>;
|
requestStatus<T extends MonitorType>(monitor: Monitor & { type: T }): Promise<MonitorStatusResponse<MonitorPayloadMap[T]>>;
|
||||||
requestWebhook(
|
requestWebhook(
|
||||||
type: string,
|
type: string,
|
||||||
url: string,
|
url: string,
|
||||||
@@ -43,12 +43,12 @@ export class NetworkService implements INetworkService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Main entry point
|
// Main entry point
|
||||||
async requestStatus(monitor: Monitor) {
|
async requestStatus<T extends MonitorType>(monitor: Monitor & { type: T }): Promise<MonitorStatusResponse<MonitorPayloadMap[T]>> {
|
||||||
const provider = this.providers.find((p) => p.supports(monitor.type));
|
const provider = this.providers.find((p) => p.supports(monitor.type));
|
||||||
if (!provider) {
|
if (!provider) {
|
||||||
return this.handleUnsupportedType(monitor.type);
|
return this.handleUnsupportedType(monitor.type) as Promise<MonitorStatusResponse<MonitorPayloadMap[T]>>;
|
||||||
}
|
}
|
||||||
return provider.handle(monitor);
|
return provider.handle(monitor) as Promise<MonitorStatusResponse<MonitorPayloadMap[T]>>;
|
||||||
}
|
}
|
||||||
|
|
||||||
private async handleUnsupportedType(type: string): Promise<MonitorStatusResponse> {
|
private async handleUnsupportedType(type: string): Promise<MonitorStatusResponse> {
|
||||||
|
|||||||
@@ -0,0 +1,274 @@
|
|||||||
|
const SERVICE_NAME = "TeamsProvider";
|
||||||
|
import type { Notification } from "@/types/index.js";
|
||||||
|
import { INotificationProvider } from "@/service/index.js";
|
||||||
|
import type { NotificationMessage } from "@/types/notificationMessage.js";
|
||||||
|
import { getTestMessage } from "@/service/infrastructure/notificationProviders/utils.js";
|
||||||
|
import type { ILogger } from "@/utils/logger.js";
|
||||||
|
import got, { HTTPError } from "got";
|
||||||
|
|
||||||
|
// Types for Adaptive Card elements
|
||||||
|
type TextBlock = {
|
||||||
|
type: "TextBlock";
|
||||||
|
text: string;
|
||||||
|
weight?: "Bolder" | "Normal" | "Lighter";
|
||||||
|
size?: "Small" | "Medium" | "Large" | "ExtraLarge";
|
||||||
|
color?: "Default" | "Dark" | "Light" | "Accent" | "Good" | "Warning" | "Attention";
|
||||||
|
wrap?: boolean;
|
||||||
|
spacing?: "None" | "Small" | "Medium" | "Large" | "ExtraLarge" | "Auto";
|
||||||
|
isSubtle?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
type ColumnSet = {
|
||||||
|
type: "ColumnSet";
|
||||||
|
separator?: boolean;
|
||||||
|
spacing?: "None" | "Small" | "Medium" | "Large" | "ExtraLarge" | "Auto";
|
||||||
|
columns: unknown[];
|
||||||
|
};
|
||||||
|
|
||||||
|
type Fact = {
|
||||||
|
title: string;
|
||||||
|
value: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
type FactSet = {
|
||||||
|
type: "FactSet";
|
||||||
|
facts: Fact[];
|
||||||
|
};
|
||||||
|
|
||||||
|
type Action = {
|
||||||
|
type: string;
|
||||||
|
title: string;
|
||||||
|
url?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
type AdaptiveCard = {
|
||||||
|
type: "AdaptiveCard";
|
||||||
|
$schema: "http://adaptivecards.io/schemas/adaptive-card.json";
|
||||||
|
version: "1.4";
|
||||||
|
body: (TextBlock | ColumnSet | FactSet)[];
|
||||||
|
actions?: Action[];
|
||||||
|
};
|
||||||
|
|
||||||
|
type TeamsMessage = {
|
||||||
|
type: "message";
|
||||||
|
attachments: Array<{
|
||||||
|
contentType: "application/vnd.microsoft.card.adaptive";
|
||||||
|
contentUrl: null;
|
||||||
|
content: AdaptiveCard;
|
||||||
|
}>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export class TeamsProvider implements INotificationProvider {
|
||||||
|
private logger: ILogger;
|
||||||
|
|
||||||
|
constructor(logger: ILogger) {
|
||||||
|
this.logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
async sendTestAlert(notification: Notification): Promise<boolean> {
|
||||||
|
if (!notification.address) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const payload = this.wrapAdaptiveCard({
|
||||||
|
type: "AdaptiveCard",
|
||||||
|
$schema: "http://adaptivecards.io/schemas/adaptive-card.json",
|
||||||
|
version: "1.4",
|
||||||
|
body: [
|
||||||
|
{
|
||||||
|
type: "TextBlock",
|
||||||
|
text: getTestMessage(),
|
||||||
|
weight: "Bolder",
|
||||||
|
size: "Medium",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
await got.post(notification.address, {
|
||||||
|
json: payload,
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return true;
|
||||||
|
} catch (error) {
|
||||||
|
const err = error as HTTPError;
|
||||||
|
this.logger.warn({
|
||||||
|
message: "Teams test alert failed",
|
||||||
|
service: SERVICE_NAME,
|
||||||
|
method: "sendTestAlert",
|
||||||
|
stack: err?.stack,
|
||||||
|
});
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async sendMessage(notification: Notification, message: NotificationMessage): Promise<boolean> {
|
||||||
|
if (!notification.address) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const payload = this.wrapAdaptiveCard(this.buildAdaptiveCard(message));
|
||||||
|
|
||||||
|
try {
|
||||||
|
await got.post(notification.address, {
|
||||||
|
json: payload,
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
this.logger.info({
|
||||||
|
message: "Teams notification sent via sendMessage",
|
||||||
|
service: SERVICE_NAME,
|
||||||
|
method: "sendMessage",
|
||||||
|
});
|
||||||
|
return true;
|
||||||
|
} catch (error) {
|
||||||
|
const err = error as HTTPError;
|
||||||
|
this.logger.warn({
|
||||||
|
message: "Teams alert failed via sendMessage",
|
||||||
|
service: SERVICE_NAME,
|
||||||
|
method: "sendMessage",
|
||||||
|
stack: err?.stack,
|
||||||
|
});
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Wrap an Adaptive Card in the Teams webhook envelope format
|
||||||
|
*/
|
||||||
|
private wrapAdaptiveCard(card: AdaptiveCard): TeamsMessage {
|
||||||
|
return {
|
||||||
|
type: "message",
|
||||||
|
attachments: [
|
||||||
|
{
|
||||||
|
contentType: "application/vnd.microsoft.card.adaptive",
|
||||||
|
contentUrl: null,
|
||||||
|
content: card,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build an Adaptive Card from NotificationMessage
|
||||||
|
*/
|
||||||
|
private buildAdaptiveCard(message: NotificationMessage): AdaptiveCard {
|
||||||
|
const colorMap: Record<string, string> = {
|
||||||
|
critical: "attention",
|
||||||
|
warning: "warning",
|
||||||
|
success: "good",
|
||||||
|
info: "accent",
|
||||||
|
};
|
||||||
|
const color = (colorMap[message.severity] || "default") as "Default" | "Dark" | "Light" | "Accent" | "Good" | "Warning" | "Attention" | undefined;
|
||||||
|
|
||||||
|
const body: (TextBlock | ColumnSet | FactSet)[] = [];
|
||||||
|
|
||||||
|
// Header with colored status indicator
|
||||||
|
body.push({
|
||||||
|
type: "TextBlock",
|
||||||
|
text: message.content.title,
|
||||||
|
weight: "Bolder",
|
||||||
|
size: "Large",
|
||||||
|
color,
|
||||||
|
wrap: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Summary
|
||||||
|
body.push({
|
||||||
|
type: "TextBlock",
|
||||||
|
text: message.content.summary,
|
||||||
|
wrap: true,
|
||||||
|
spacing: "Small",
|
||||||
|
});
|
||||||
|
|
||||||
|
// Separator
|
||||||
|
body.push({
|
||||||
|
type: "ColumnSet",
|
||||||
|
separator: true,
|
||||||
|
spacing: "Medium",
|
||||||
|
columns: [],
|
||||||
|
});
|
||||||
|
|
||||||
|
// Monitor details as a FactSet
|
||||||
|
body.push({
|
||||||
|
type: "FactSet",
|
||||||
|
facts: [
|
||||||
|
{ title: "Name", value: message.monitor.name },
|
||||||
|
{ title: "Type", value: message.monitor.type },
|
||||||
|
{ title: "Status", value: message.monitor.status },
|
||||||
|
{ title: "URL", value: message.monitor.url },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
// Threshold breaches
|
||||||
|
if (message.content.thresholds && message.content.thresholds.length > 0) {
|
||||||
|
body.push({
|
||||||
|
type: "TextBlock",
|
||||||
|
text: "**Threshold Breaches**",
|
||||||
|
weight: "Bolder",
|
||||||
|
spacing: "Medium",
|
||||||
|
wrap: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const breach of message.content.thresholds) {
|
||||||
|
body.push({
|
||||||
|
type: "TextBlock",
|
||||||
|
text: `• **${breach.metric.toUpperCase()}**: ${breach.formattedValue} (threshold: ${breach.threshold}${breach.unit})`,
|
||||||
|
wrap: true,
|
||||||
|
spacing: "Small",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Additional details
|
||||||
|
if (message.content.details && message.content.details.length > 0) {
|
||||||
|
body.push({
|
||||||
|
type: "TextBlock",
|
||||||
|
text: "**Additional Information**",
|
||||||
|
weight: "Bolder",
|
||||||
|
spacing: "Medium",
|
||||||
|
wrap: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const detail of message.content.details) {
|
||||||
|
body.push({
|
||||||
|
type: "TextBlock",
|
||||||
|
text: `• ${detail}`,
|
||||||
|
wrap: true,
|
||||||
|
spacing: "Small",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Timestamp footer
|
||||||
|
body.push({
|
||||||
|
type: "TextBlock",
|
||||||
|
text: `Checkmate | ${new Date(message.content.timestamp).toUTCString()}`,
|
||||||
|
size: "Small",
|
||||||
|
isSubtle: true,
|
||||||
|
spacing: "Medium",
|
||||||
|
wrap: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Actions (incident link)
|
||||||
|
const actions: Action[] = [];
|
||||||
|
if (message.content.incident) {
|
||||||
|
actions.push({
|
||||||
|
type: "Action.OpenUrl",
|
||||||
|
title: "View Incident",
|
||||||
|
url: `${message.clientHost}/incidents/${message.content.incident.id}`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
type: "AdaptiveCard",
|
||||||
|
$schema: "http://adaptivecards.io/schemas/adaptive-card.json",
|
||||||
|
version: "1.4",
|
||||||
|
body,
|
||||||
|
...(actions.length > 0 ? { actions } : {}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -32,6 +32,7 @@ export class NotificationsService implements INotificationsService {
|
|||||||
private discordProvider: INotificationProvider;
|
private discordProvider: INotificationProvider;
|
||||||
private pagerDutyProvider: INotificationProvider;
|
private pagerDutyProvider: INotificationProvider;
|
||||||
private matrixProvider: INotificationProvider;
|
private matrixProvider: INotificationProvider;
|
||||||
|
private teamsProvider: INotificationProvider;
|
||||||
private logger: ILogger;
|
private logger: ILogger;
|
||||||
private settingsService: ISettingsService;
|
private settingsService: ISettingsService;
|
||||||
private notificationMessageBuilder: INotificationMessageBuilder;
|
private notificationMessageBuilder: INotificationMessageBuilder;
|
||||||
@@ -45,6 +46,7 @@ export class NotificationsService implements INotificationsService {
|
|||||||
discordProvider: INotificationProvider,
|
discordProvider: INotificationProvider,
|
||||||
pagerDutyProvider: INotificationProvider,
|
pagerDutyProvider: INotificationProvider,
|
||||||
matrixProvider: INotificationProvider,
|
matrixProvider: INotificationProvider,
|
||||||
|
teamsProvider: INotificationProvider,
|
||||||
settingsService: ISettingsService,
|
settingsService: ISettingsService,
|
||||||
logger: ILogger,
|
logger: ILogger,
|
||||||
notificationMessageBuilder: INotificationMessageBuilder
|
notificationMessageBuilder: INotificationMessageBuilder
|
||||||
@@ -57,6 +59,7 @@ export class NotificationsService implements INotificationsService {
|
|||||||
this.discordProvider = discordProvider;
|
this.discordProvider = discordProvider;
|
||||||
this.pagerDutyProvider = pagerDutyProvider;
|
this.pagerDutyProvider = pagerDutyProvider;
|
||||||
this.matrixProvider = matrixProvider;
|
this.matrixProvider = matrixProvider;
|
||||||
|
this.teamsProvider = teamsProvider;
|
||||||
this.settingsService = settingsService;
|
this.settingsService = settingsService;
|
||||||
this.logger = logger;
|
this.logger = logger;
|
||||||
this.notificationMessageBuilder = notificationMessageBuilder;
|
this.notificationMessageBuilder = notificationMessageBuilder;
|
||||||
@@ -92,6 +95,8 @@ export class NotificationsService implements INotificationsService {
|
|||||||
return await this.discordProvider.sendMessage!(notification, notificationMessage);
|
return await this.discordProvider.sendMessage!(notification, notificationMessage);
|
||||||
case "email":
|
case "email":
|
||||||
return await this.emailProvider.sendMessage!(notification, notificationMessage);
|
return await this.emailProvider.sendMessage!(notification, notificationMessage);
|
||||||
|
case "teams":
|
||||||
|
return await this.teamsProvider.sendMessage!(notification, notificationMessage);
|
||||||
default:
|
default:
|
||||||
this.logger.warn({
|
this.logger.warn({
|
||||||
message: `Unknown notification type: ${notification.type}`,
|
message: `Unknown notification type: ${notification.type}`,
|
||||||
@@ -150,6 +155,8 @@ export class NotificationsService implements INotificationsService {
|
|||||||
return await this.matrixProvider.sendTestAlert(notification);
|
return await this.matrixProvider.sendTestAlert(notification);
|
||||||
case "webhook":
|
case "webhook":
|
||||||
return await this.webhookProvider.sendTestAlert(notification);
|
return await this.webhookProvider.sendTestAlert(notification);
|
||||||
|
case "teams":
|
||||||
|
return await this.teamsProvider.sendTestAlert(notification);
|
||||||
default:
|
default:
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,12 +2,12 @@ import { ISettingsRepository } from "@/repositories/index.js";
|
|||||||
import { Settings } from "@/types/index.js";
|
import { Settings } from "@/types/index.js";
|
||||||
import { AppError } from "@/utils/AppError.js";
|
import { AppError } from "@/utils/AppError.js";
|
||||||
import { ValidatedEnv } from "@/validation/envValidation.js";
|
import { ValidatedEnv } from "@/validation/envValidation.js";
|
||||||
|
import type { StringValue } from "ms";
|
||||||
const SERVICE_NAME = "SettingsService";
|
const SERVICE_NAME = "SettingsService";
|
||||||
|
|
||||||
export type EnvConfig = {
|
export type EnvConfig = {
|
||||||
jwtSecret: string;
|
jwtSecret: string;
|
||||||
jwtTTL: string;
|
jwtTTL: StringValue;
|
||||||
nodeEnv: string;
|
nodeEnv: string;
|
||||||
logLevel: string;
|
logLevel: string;
|
||||||
clientHost: string;
|
clientHost: string;
|
||||||
@@ -30,7 +30,7 @@ export class SettingsService implements ISettingsService {
|
|||||||
this.settingsRepository = settingsRepository;
|
this.settingsRepository = settingsRepository;
|
||||||
this.settings = {
|
this.settings = {
|
||||||
jwtSecret: env.JWT_SECRET,
|
jwtSecret: env.JWT_SECRET,
|
||||||
jwtTTL: env.TOKEN_TTL,
|
jwtTTL: env.TOKEN_TTL as StringValue,
|
||||||
nodeEnv: env.NODE_ENV,
|
nodeEnv: env.NODE_ENV,
|
||||||
logLevel: env.LOG_LEVEL,
|
logLevel: env.LOG_LEVEL,
|
||||||
clientHost: env.CLIENT_HOST,
|
clientHost: env.CLIENT_HOST,
|
||||||
|
|||||||
@@ -1,5 +1,8 @@
|
|||||||
import type { MonitorType } from "@/types/index.js";
|
import type { MonitorType } from "@/types/index.js";
|
||||||
import type { Response } from "got";
|
import type { Response } from "got";
|
||||||
|
|
||||||
|
export const CHECK_TTL_SENTINEL = 366;
|
||||||
|
|
||||||
export type GotTimings = Response["timings"];
|
export type GotTimings = Response["timings"];
|
||||||
|
|
||||||
export interface CheckMetadata {
|
export interface CheckMetadata {
|
||||||
@@ -98,9 +101,6 @@ export interface Check {
|
|||||||
timings?: GotTimings;
|
timings?: GotTimings;
|
||||||
statusCode: number;
|
statusCode: number;
|
||||||
message: string;
|
message: string;
|
||||||
ack: boolean;
|
|
||||||
ackAt?: string | null;
|
|
||||||
expiry: string;
|
|
||||||
cpu?: CheckCpuInfo;
|
cpu?: CheckCpuInfo;
|
||||||
memory?: CheckMemoryInfo;
|
memory?: CheckMemoryInfo;
|
||||||
disk?: CheckDiskInfo[];
|
disk?: CheckDiskInfo[];
|
||||||
@@ -113,7 +113,6 @@ export interface Check {
|
|||||||
seo?: number;
|
seo?: number;
|
||||||
performance?: number;
|
performance?: number;
|
||||||
audits?: CheckAudits;
|
audits?: CheckAudits;
|
||||||
__v: number;
|
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
updatedAt: string;
|
updatedAt: string;
|
||||||
}
|
}
|
||||||
@@ -205,4 +204,4 @@ export type NormalizedUptimeCheck<T extends GroupedCheck = GroupedCheck> = T & {
|
|||||||
originalAvgResponseTime: number;
|
originalAvgResponseTime: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type CheckSnapshot = Omit<Check, "metadata" | "ack" | "ackAt" | "expiry" | "__v" | "updatedAt">;
|
export type CheckSnapshot = Omit<Check, "metadata" | "updatedAt">;
|
||||||
@@ -126,7 +126,7 @@ export interface MonitorPayloadMap {
|
|||||||
game: GameStatusPayload;
|
game: GameStatusPayload;
|
||||||
grpc: GrpcStatusPayload;
|
grpc: GrpcStatusPayload;
|
||||||
websocket: WebSocketStatusPayload;
|
websocket: WebSocketStatusPayload;
|
||||||
default: unknown;
|
unknown: unknown;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type StatusChangeResult = {
|
export type StatusChangeResult = {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
export const NotificationChannels = ["email", "slack", "discord", "webhook", "pager_duty", "matrix"] as const;
|
export const NotificationChannels = ["email", "slack", "discord", "webhook", "pager_duty", "matrix", "teams"] as const;
|
||||||
export type NotificationChannel = (typeof NotificationChannels)[number];
|
export type NotificationChannel = (typeof NotificationChannels)[number];
|
||||||
|
|
||||||
export interface Notification {
|
export interface Notification {
|
||||||
|
|||||||
Vendored
+24
@@ -0,0 +1,24 @@
|
|||||||
|
declare module "ssl-checker" {
|
||||||
|
import { Agent } from "https";
|
||||||
|
|
||||||
|
export interface SSLDetails {
|
||||||
|
daysRemaining: number;
|
||||||
|
valid: boolean;
|
||||||
|
validFrom: string;
|
||||||
|
validTo: string;
|
||||||
|
validFor: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SSLOptions {
|
||||||
|
method?: "GET" | "HEAD";
|
||||||
|
port?: number;
|
||||||
|
agent?: Agent;
|
||||||
|
rejectUnauthorized?: boolean;
|
||||||
|
validateSubjectAltName?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
function sslChecker(hostname: string, options?: SSLOptions): Promise<SSLDetails>;
|
||||||
|
|
||||||
|
// Change 'export default' to 'export =' to allow it to be callable
|
||||||
|
export = sslChecker;
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
export const StatusPageTypes = ["uptime"] as const;
|
export const StatusPageTypes = ["uptime", "infrastructure"] as const;
|
||||||
export type StatusPageType = (typeof StatusPageTypes)[number];
|
export type StatusPageType = (typeof StatusPageTypes)[number];
|
||||||
|
|
||||||
export interface StatusPageLogo {
|
export interface StatusPageLogo {
|
||||||
@@ -15,7 +15,7 @@ export interface StatusPage {
|
|||||||
id: string;
|
id: string;
|
||||||
userId: string;
|
userId: string;
|
||||||
teamId: string;
|
teamId: string;
|
||||||
type: StatusPageType;
|
type: StatusPageType[];
|
||||||
companyName: string;
|
companyName: string;
|
||||||
url: string;
|
url: string;
|
||||||
timezone?: string;
|
timezone?: string;
|
||||||
@@ -28,6 +28,7 @@ export interface StatusPage {
|
|||||||
showCharts: boolean;
|
showCharts: boolean;
|
||||||
showUptimePercentage: boolean;
|
showUptimePercentage: boolean;
|
||||||
showAdminLoginLink: boolean;
|
showAdminLoginLink: boolean;
|
||||||
|
showInfrastructure: boolean;
|
||||||
customCSS: string;
|
customCSS: string;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
updatedAt: string;
|
updatedAt: string;
|
||||||
|
|||||||
@@ -12,33 +12,31 @@ export const getChecksParamValidation = z.object({
|
|||||||
|
|
||||||
export const getChecksQueryValidation = z.object({
|
export const getChecksQueryValidation = z.object({
|
||||||
type: z.enum(["http", "ping", "pagespeed", "hardware", "docker", "port", "game", "grpc", "websocket"]).optional(),
|
type: z.enum(["http", "ping", "pagespeed", "hardware", "docker", "port", "game", "grpc", "websocket"]).optional(),
|
||||||
sortOrder: z.enum(["asc", "desc"]).optional(),
|
sortOrder: z.enum(["asc", "desc"]),
|
||||||
limit: z.coerce.number().optional(),
|
limit: z.coerce.number().optional(),
|
||||||
dateRange: z.enum(["recent", "hour", "day", "week", "month", "all"]).optional(),
|
dateRange: z.enum(["recent", "hour", "day", "week", "month", "all"]),
|
||||||
filter: z.enum(["all", "up", "down", "resolve"]).optional(),
|
filter: z.enum(["all", "up", "down", "resolve"]).optional(),
|
||||||
ack: booleanCoercion.optional(),
|
ack: booleanCoercion.optional(),
|
||||||
page: z.coerce.number().optional(),
|
page: z.coerce.number(),
|
||||||
rowsPerPage: z.coerce.number().optional(),
|
rowsPerPage: z.coerce.number(),
|
||||||
status: booleanCoercion.optional(),
|
status: booleanCoercion.optional(),
|
||||||
continent: z.union([z.enum(GeoContinents), z.array(z.enum(GeoContinents))]).optional(),
|
continent: z.union([z.enum(GeoContinents), z.array(z.enum(GeoContinents))]).optional(),
|
||||||
});
|
});
|
||||||
|
|
||||||
export const getTeamChecksQueryValidation = z.object({
|
export const getTeamChecksQueryValidation = z.object({
|
||||||
sortOrder: z.enum(["asc", "desc"]).optional(),
|
sortOrder: z.enum(["asc", "desc"]),
|
||||||
limit: z.coerce.number().optional(),
|
limit: z.coerce.number().optional(),
|
||||||
dateRange: z.enum(["recent", "hour", "day", "week", "month", "all"]).optional(),
|
dateRange: z.enum(["recent", "hour", "day", "week", "month", "all"]),
|
||||||
filter: z.enum(["all", "up", "down", "resolve"]).optional(),
|
filter: z.enum(["all", "up", "down", "resolve"]).optional(),
|
||||||
ack: booleanCoercion.optional(),
|
ack: booleanCoercion.optional(),
|
||||||
page: z.coerce.number().optional(),
|
page: z.coerce.number(),
|
||||||
rowsPerPage: z.coerce.number().optional(),
|
rowsPerPage: z.coerce.number(),
|
||||||
});
|
});
|
||||||
|
|
||||||
export const deleteChecksParamValidation = z.object({
|
export const deleteChecksParamValidation = z.object({
|
||||||
monitorId: z.string().min(1, "Monitor ID is required"),
|
monitorId: z.string().min(1, "Monitor ID is required"),
|
||||||
});
|
});
|
||||||
|
|
||||||
export const deleteChecksByTeamIdParamValidation = z.object({});
|
export const getChecksSummaryByTeamIdQueryValidation = z.object({
|
||||||
|
dateRange: z.enum(["recent", "hour", "day", "week", "month", "all"]).optional(),
|
||||||
export const updateChecksTTLBodyValidation = z.object({
|
|
||||||
ttl: z.number().min(1, "TTL is required"),
|
|
||||||
});
|
});
|
||||||
@@ -18,7 +18,7 @@ export const createNotificationBodyValidation = z.discriminatedUnion("type", [
|
|||||||
z.object({
|
z.object({
|
||||||
notificationName: z.string().min(1, "Notification name is required"),
|
notificationName: z.string().min(1, "Notification name is required"),
|
||||||
type: z.literal("webhook"),
|
type: z.literal("webhook"),
|
||||||
address: z.string().url("Please enter a valid Webhook URL"),
|
address: z.url({ message: "Please enter a valid Webhook URL" }),
|
||||||
homeserverUrl: z.union([z.string(), z.literal("")]).optional(),
|
homeserverUrl: z.union([z.string(), z.literal("")]).optional(),
|
||||||
roomId: z.union([z.string(), z.literal("")]).optional(),
|
roomId: z.union([z.string(), z.literal("")]).optional(),
|
||||||
accessToken: z.union([z.string(), z.literal("")]).optional(),
|
accessToken: z.union([z.string(), z.literal("")]).optional(),
|
||||||
@@ -27,7 +27,7 @@ export const createNotificationBodyValidation = z.discriminatedUnion("type", [
|
|||||||
z.object({
|
z.object({
|
||||||
notificationName: z.string().min(1, "Notification name is required"),
|
notificationName: z.string().min(1, "Notification name is required"),
|
||||||
type: z.literal("slack"),
|
type: z.literal("slack"),
|
||||||
address: z.string().url("Please enter a valid Webhook URL"),
|
address: z.url({ message: "Please enter a valid Webhook URL" }),
|
||||||
homeserverUrl: z.union([z.string(), z.literal("")]).optional(),
|
homeserverUrl: z.union([z.string(), z.literal("")]).optional(),
|
||||||
roomId: z.union([z.string(), z.literal("")]).optional(),
|
roomId: z.union([z.string(), z.literal("")]).optional(),
|
||||||
accessToken: z.union([z.string(), z.literal("")]).optional(),
|
accessToken: z.union([z.string(), z.literal("")]).optional(),
|
||||||
@@ -36,7 +36,7 @@ export const createNotificationBodyValidation = z.discriminatedUnion("type", [
|
|||||||
z.object({
|
z.object({
|
||||||
notificationName: z.string().min(1, "Notification name is required"),
|
notificationName: z.string().min(1, "Notification name is required"),
|
||||||
type: z.literal("discord"),
|
type: z.literal("discord"),
|
||||||
address: z.string().url("Please enter a valid Webhook URL"),
|
address: z.url({ message: "Please enter a valid Webhook URL" }),
|
||||||
homeserverUrl: z.union([z.string(), z.literal("")]).optional(),
|
homeserverUrl: z.union([z.string(), z.literal("")]).optional(),
|
||||||
roomId: z.union([z.string(), z.literal("")]).optional(),
|
roomId: z.union([z.string(), z.literal("")]).optional(),
|
||||||
accessToken: z.union([z.string(), z.literal("")]).optional(),
|
accessToken: z.union([z.string(), z.literal("")]).optional(),
|
||||||
@@ -55,10 +55,16 @@ export const createNotificationBodyValidation = z.discriminatedUnion("type", [
|
|||||||
notificationName: z.string().min(1, "Notification name is required"),
|
notificationName: z.string().min(1, "Notification name is required"),
|
||||||
type: z.literal("matrix"),
|
type: z.literal("matrix"),
|
||||||
address: z.union([z.string(), z.literal("")]).optional(),
|
address: z.union([z.string(), z.literal("")]).optional(),
|
||||||
homeserverUrl: z.string().url("Please enter a valid Homeserver URL"),
|
homeserverUrl: z.url({ message: "Please enter a valid Homeserver URL" }),
|
||||||
roomId: z.string().min(1, "Room ID is required"),
|
roomId: z.string().min(1, "Room ID is required"),
|
||||||
accessToken: z.string().min(1, "Access Token is required"),
|
accessToken: z.string().min(1, "Access Token is required"),
|
||||||
}),
|
}),
|
||||||
|
// Teams notification
|
||||||
|
z.object({
|
||||||
|
notificationName: z.string().min(1, "Notification name is required"),
|
||||||
|
type: z.literal("teams"),
|
||||||
|
address: z.url({ message: "Please enter a valid Webhook URL" }),
|
||||||
|
}),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
export const sendTestEmailBodyValidation = z.object({
|
export const sendTestEmailBodyValidation = z.object({
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { CHECK_TTL_SENTINEL } from "@/types/check.js";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
|
|
||||||
//****************************************
|
//****************************************
|
||||||
@@ -6,9 +7,8 @@ import { z } from "zod";
|
|||||||
|
|
||||||
export const updateAppSettingsBodyValidation = z
|
export const updateAppSettingsBodyValidation = z
|
||||||
.object({
|
.object({
|
||||||
checkTTL: z.union([z.number(), z.literal("")]).optional(),
|
checkTTL: z.union([z.number().int().min(1).max(CHECK_TTL_SENTINEL), z.literal("")]).optional(),
|
||||||
systemEmailPort: z.union([z.number(), z.literal("")]).optional(),
|
systemEmailPort: z.union([z.number(), z.literal("")]).optional(),
|
||||||
|
|
||||||
pagespeedApiKey: z.union([z.string(), z.literal("")]).optional(),
|
pagespeedApiKey: z.union([z.string(), z.literal("")]).optional(),
|
||||||
language: z.union([z.string(), z.literal("")]).optional(),
|
language: z.union([z.string(), z.literal("")]).optional(),
|
||||||
timezone: z.union([z.string(), z.literal("")]).optional(),
|
timezone: z.union([z.string(), z.literal("")]).optional(),
|
||||||
|
|||||||
@@ -10,13 +10,13 @@ export const getStatusPageParamValidation = z.object({
|
|||||||
});
|
});
|
||||||
|
|
||||||
export const getStatusPageQueryValidation = z.object({
|
export const getStatusPageQueryValidation = z.object({
|
||||||
type: z.literal("uptime"),
|
type: z.array(z.enum(["uptime", "infrastructure"])),
|
||||||
timeFrame: z.coerce.number().optional(),
|
timeFrame: z.coerce.number().optional(),
|
||||||
});
|
});
|
||||||
|
|
||||||
export const createStatusPageBodyValidation = z
|
export const createStatusPageBodyValidation = z
|
||||||
.object({
|
.object({
|
||||||
type: z.literal("uptime"),
|
type: z.array(z.enum(["uptime", "infrastructure"])),
|
||||||
companyName: z.string().min(1, "Company name is required"),
|
companyName: z.string().min(1, "Company name is required"),
|
||||||
url: z.string().regex(/^[a-zA-Z0-9_-]+$/, {
|
url: z.string().regex(/^[a-zA-Z0-9_-]+$/, {
|
||||||
message: "URL can only contain letters, numbers, underscores, and hyphens",
|
message: "URL can only contain letters, numbers, underscores, and hyphens",
|
||||||
|
|||||||
@@ -0,0 +1,267 @@
|
|||||||
|
import { describe, expect, it, jest, beforeEach } from "@jest/globals";
|
||||||
|
import { TeamsProvider } from "../src/service/infrastructure/notificationProviders/teams.ts";
|
||||||
|
import type { Notification } from "../src/types/notification.ts";
|
||||||
|
import type { NotificationMessage } from "../src/types/notificationMessage.ts";
|
||||||
|
|
||||||
|
// Mock got
|
||||||
|
jest.unstable_mockModule("got", () => ({
|
||||||
|
default: { post: jest.fn() },
|
||||||
|
}));
|
||||||
|
|
||||||
|
const createLogger = () => ({
|
||||||
|
info: jest.fn(),
|
||||||
|
warn: jest.fn(),
|
||||||
|
error: jest.fn(),
|
||||||
|
debug: jest.fn(),
|
||||||
|
});
|
||||||
|
|
||||||
|
const createNotification = (overrides?: Partial<Notification>): Notification => ({
|
||||||
|
id: "notif-1",
|
||||||
|
userId: "user-1",
|
||||||
|
teamId: "team-1",
|
||||||
|
type: "teams",
|
||||||
|
notificationName: "Teams Alert",
|
||||||
|
address: "https://xxxxx.webhook.office.com/webhookb2/test",
|
||||||
|
createdAt: new Date().toISOString(),
|
||||||
|
updatedAt: new Date().toISOString(),
|
||||||
|
...overrides,
|
||||||
|
});
|
||||||
|
|
||||||
|
const createMessage = (overrides?: Partial<NotificationMessage>): NotificationMessage => ({
|
||||||
|
type: "monitor_down",
|
||||||
|
severity: "critical",
|
||||||
|
monitor: {
|
||||||
|
id: "mon-1",
|
||||||
|
name: "API Server",
|
||||||
|
url: "https://api.example.com",
|
||||||
|
type: "http",
|
||||||
|
status: "down",
|
||||||
|
},
|
||||||
|
content: {
|
||||||
|
title: "🔴 Monitor Down",
|
||||||
|
summary: "API Server is not responding",
|
||||||
|
details: ["Response timeout after 30s"],
|
||||||
|
thresholds: [],
|
||||||
|
incident: {
|
||||||
|
id: "inc-1",
|
||||||
|
url: "https://app.example.com/incidents/inc-1",
|
||||||
|
createdAt: new Date(),
|
||||||
|
},
|
||||||
|
timestamp: new Date("2026-01-15T12:00:00Z"),
|
||||||
|
},
|
||||||
|
clientHost: "https://app.example.com",
|
||||||
|
metadata: {
|
||||||
|
teamId: "team-1",
|
||||||
|
notificationReason: "monitor_down",
|
||||||
|
},
|
||||||
|
...overrides,
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("TeamsProvider", () => {
|
||||||
|
let provider: TeamsProvider;
|
||||||
|
let logger: ReturnType<typeof createLogger>;
|
||||||
|
let gotPost: jest.Mock;
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
logger = createLogger();
|
||||||
|
provider = new TeamsProvider(logger);
|
||||||
|
const got = await import("got");
|
||||||
|
gotPost = got.default.post as jest.Mock;
|
||||||
|
gotPost.mockReset();
|
||||||
|
gotPost.mockResolvedValue({});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("sendTestAlert", () => {
|
||||||
|
it("returns false when address is missing", async () => {
|
||||||
|
const notification = createNotification({ address: undefined });
|
||||||
|
const result = await provider.sendTestAlert(notification);
|
||||||
|
expect(result).toBe(false);
|
||||||
|
expect(gotPost).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("sends an Adaptive Card test message and returns true on success", async () => {
|
||||||
|
const notification = createNotification();
|
||||||
|
const result = await provider.sendTestAlert(notification);
|
||||||
|
expect(result).toBe(true);
|
||||||
|
expect(gotPost).toHaveBeenCalledTimes(1);
|
||||||
|
|
||||||
|
const [url, options] = gotPost.mock.calls[0] as [string, { json: any; headers: any }];
|
||||||
|
expect(url).toBe(notification.address);
|
||||||
|
expect(options.headers["Content-Type"]).toBe("application/json");
|
||||||
|
|
||||||
|
// Verify Teams webhook envelope
|
||||||
|
const payload = options.json;
|
||||||
|
expect(payload.type).toBe("message");
|
||||||
|
expect(payload.attachments).toHaveLength(1);
|
||||||
|
expect(payload.attachments[0].contentType).toBe("application/vnd.microsoft.card.adaptive");
|
||||||
|
|
||||||
|
// Verify Adaptive Card structure
|
||||||
|
const card = payload.attachments[0].content;
|
||||||
|
expect(card.type).toBe("AdaptiveCard");
|
||||||
|
expect(card.version).toBe("1.4");
|
||||||
|
expect(card.body[0].type).toBe("TextBlock");
|
||||||
|
expect(card.body[0].text).toContain("test notification");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns false and logs warning on HTTP error", async () => {
|
||||||
|
gotPost.mockRejectedValue(new Error("Network error"));
|
||||||
|
const notification = createNotification();
|
||||||
|
const result = await provider.sendTestAlert(notification);
|
||||||
|
expect(result).toBe(false);
|
||||||
|
expect(logger.warn).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
message: "Teams test alert failed",
|
||||||
|
service: "TeamsProvider",
|
||||||
|
})
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("sendMessage", () => {
|
||||||
|
it("returns false when address is missing", async () => {
|
||||||
|
const notification = createNotification({ address: undefined });
|
||||||
|
const result = await provider.sendMessage(notification, createMessage());
|
||||||
|
expect(result).toBe(false);
|
||||||
|
expect(gotPost).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("sends a well-formed Adaptive Card and returns true", async () => {
|
||||||
|
const notification = createNotification();
|
||||||
|
const message = createMessage();
|
||||||
|
const result = await provider.sendMessage(notification, message);
|
||||||
|
|
||||||
|
expect(result).toBe(true);
|
||||||
|
expect(gotPost).toHaveBeenCalledTimes(1);
|
||||||
|
|
||||||
|
const [url, options] = gotPost.mock.calls[0] as [string, { json: any }];
|
||||||
|
expect(url).toBe(notification.address);
|
||||||
|
|
||||||
|
const payload = options.json;
|
||||||
|
expect(payload.type).toBe("message");
|
||||||
|
|
||||||
|
const card = payload.attachments[0].content;
|
||||||
|
expect(card.type).toBe("AdaptiveCard");
|
||||||
|
expect(card.version).toBe("1.4");
|
||||||
|
|
||||||
|
// Verify body contains expected elements
|
||||||
|
const textBlocks = card.body.filter((b: any) => b.type === "TextBlock");
|
||||||
|
const factSets = card.body.filter((b: any) => b.type === "FactSet");
|
||||||
|
|
||||||
|
// Title block
|
||||||
|
expect(textBlocks[0].text).toBe(message.content.title);
|
||||||
|
expect(textBlocks[0].color).toBe("attention"); // critical -> attention
|
||||||
|
|
||||||
|
// Summary block
|
||||||
|
expect(textBlocks[1].text).toBe(message.content.summary);
|
||||||
|
|
||||||
|
// FactSet with monitor details
|
||||||
|
expect(factSets).toHaveLength(1);
|
||||||
|
const facts = factSets[0].facts;
|
||||||
|
expect(facts).toEqual(
|
||||||
|
expect.arrayContaining([
|
||||||
|
expect.objectContaining({ title: "Name", value: "API Server" }),
|
||||||
|
expect.objectContaining({ title: "URL", value: "https://api.example.com" }),
|
||||||
|
expect.objectContaining({ title: "Status", value: "down" }),
|
||||||
|
])
|
||||||
|
);
|
||||||
|
|
||||||
|
// Incident action button
|
||||||
|
expect(card.actions).toHaveLength(1);
|
||||||
|
expect(card.actions[0].type).toBe("Action.OpenUrl");
|
||||||
|
expect(card.actions[0].title).toBe("View Incident");
|
||||||
|
expect(card.actions[0].url).toContain("/infrastructure/mon-1");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("omits actions when no incident is present", async () => {
|
||||||
|
const notification = createNotification();
|
||||||
|
const message = createMessage({
|
||||||
|
content: {
|
||||||
|
title: "Test",
|
||||||
|
summary: "Summary",
|
||||||
|
timestamp: new Date(),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const result = await provider.sendMessage(notification, message);
|
||||||
|
expect(result).toBe(true);
|
||||||
|
|
||||||
|
const [, options] = gotPost.mock.calls[0] as [string, { json: any }];
|
||||||
|
const card = options.json.attachments[0].content;
|
||||||
|
expect(card.actions).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("includes threshold breaches when present", async () => {
|
||||||
|
const notification = createNotification();
|
||||||
|
const message = createMessage({
|
||||||
|
type: "threshold_breach",
|
||||||
|
severity: "warning",
|
||||||
|
content: {
|
||||||
|
title: "Threshold Breach",
|
||||||
|
summary: "CPU usage exceeded",
|
||||||
|
thresholds: [
|
||||||
|
{
|
||||||
|
metric: "cpu",
|
||||||
|
currentValue: 95,
|
||||||
|
threshold: 80,
|
||||||
|
unit: "%",
|
||||||
|
formattedValue: "95%",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
timestamp: new Date(),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await provider.sendMessage(notification, message);
|
||||||
|
|
||||||
|
const [, options] = gotPost.mock.calls[0] as [string, { json: any }];
|
||||||
|
const card = options.json.attachments[0].content;
|
||||||
|
|
||||||
|
// Title should use "warning" color
|
||||||
|
expect(card.body[0].color).toBe("warning");
|
||||||
|
|
||||||
|
// Find threshold text blocks
|
||||||
|
const thresholdHeader = card.body.find((b: any) => b.type === "TextBlock" && b.text === "**Threshold Breaches**");
|
||||||
|
expect(thresholdHeader).toBeDefined();
|
||||||
|
|
||||||
|
const cpuBlock = card.body.find((b: any) => b.type === "TextBlock" && b.text?.includes("CPU"));
|
||||||
|
expect(cpuBlock).toBeDefined();
|
||||||
|
expect(cpuBlock.text).toContain("95%");
|
||||||
|
expect(cpuBlock.text).toContain("threshold: 80%");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("maps severity to correct Adaptive Card colors", async () => {
|
||||||
|
const notification = createNotification();
|
||||||
|
|
||||||
|
const severityMap = [
|
||||||
|
{ severity: "critical", expected: "attention" },
|
||||||
|
{ severity: "warning", expected: "warning" },
|
||||||
|
{ severity: "success", expected: "good" },
|
||||||
|
{ severity: "info", expected: "accent" },
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
for (const { severity, expected } of severityMap) {
|
||||||
|
gotPost.mockReset();
|
||||||
|
gotPost.mockResolvedValue({});
|
||||||
|
|
||||||
|
const message = createMessage({ severity });
|
||||||
|
await provider.sendMessage(notification, message);
|
||||||
|
|
||||||
|
const [, options] = gotPost.mock.calls[0] as [string, { json: any }];
|
||||||
|
const card = options.json.attachments[0].content;
|
||||||
|
expect(card.body[0].color).toBe(expected);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns false and logs warning on HTTP error", async () => {
|
||||||
|
gotPost.mockRejectedValue(new Error("502 Bad Gateway"));
|
||||||
|
const notification = createNotification();
|
||||||
|
const result = await provider.sendMessage(notification, createMessage());
|
||||||
|
expect(result).toBe(false);
|
||||||
|
expect(logger.warn).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
message: "Teams alert failed via sendMessage",
|
||||||
|
service: "TeamsProvider",
|
||||||
|
})
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -14,7 +14,8 @@
|
|||||||
"moduleResolution": "nodenext",
|
"moduleResolution": "nodenext",
|
||||||
"skipLibCheck": true,
|
"skipLibCheck": true,
|
||||||
"noUncheckedIndexedAccess": true,
|
"noUncheckedIndexedAccess": true,
|
||||||
"isolatedModules": true
|
"isolatedModules": true,
|
||||||
|
"resolveJsonModule": true
|
||||||
},
|
},
|
||||||
"include": ["src"],
|
"include": ["src"],
|
||||||
"exclude": ["tests", "dist", "node_modules"]
|
"exclude": ["tests", "dist", "node_modules"]
|
||||||
|
|||||||
Reference in new issue
Block a user