diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 000000000..1535e84cf --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,145 @@ +# CLAUDE.md + +This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. + +## Project Overview + +Checkmate is an open-source uptime and infrastructure monitoring application. It monitors server hardware, uptime, response times, and incidents with real-time alerts. The companion agent [Capture](https://github.com/bluewave-labs/capture) provides infrastructure metrics (CPU, RAM, disk, temperature). + +## Development Commands + +### Client (React/Vite) +```bash +cd client +npm install +npm run dev # Start dev server at http://localhost:5173 +npm run build # TypeScript check + production build +npm run lint # ESLint (strict, max-warnings 0) +npm run format # Prettier formatting +npm run format-check # Check formatting +``` + +### Server (Node.js/Express) +```bash +cd server +npm install +npm run dev # Start with hot-reload (nodemon + tsx) at http://localhost:52345 +npm run build # TypeScript compile + path alias resolution +npm run test # Run Mocha tests with c8 coverage +npm run lint # ESLint v9 +npm run lint-fix # Auto-fix lint issues +npm run format # Prettier formatting +``` + +### Docker Development +```bash +cd docker/dev +./build_images.sh +docker run -d -p 27017:27017 -v uptime_mongo_data:/data/db --name uptime_database_mongo mongo:6.0 +``` + +## Environment Setup + +### Server `.env` (minimum required) +```env +CLIENT_HOST="http://localhost:5173" +JWT_SECRET="my_secret_key_change_this" +DB_CONNECTION_STRING="mongodb://localhost:27017/uptime_db" +TOKEN_TTL="99d" +ORIGIN="localhost" +LOG_LEVEL="debug" +``` + +### Client `.env` +```env +VITE_APP_API_BASE_URL="http://localhost:52345/api/v1" +VITE_APP_LOG_LEVEL="debug" +``` + +## Architecture + +### Monorepo Structure +- `/client` - React 18 + TypeScript + Vite + MUI frontend +- `/server` - Node.js 20+ + Express + TypeScript backend +- `/docker` - Multi-environment Docker configs (dev, staging, prod, arm, mono) + +### Backend Layers +``` +server/src/ +├── controllers/ # Route handlers (authController, monitorController, etc.) +├── service/ # Business logic +│ ├── business/ # Core monitoring logic +│ ├── infrastructure/ # Server/system utilities +│ └── system/ # App-level settings +├── db/ +│ ├── models/ # Mongoose schemas (Monitor, Check, Incident, User, etc.) +│ ├── migration/ # Database migrations (run on startup) +│ └── modules/ # Database-specific modules +├── middleware/v1/ # verifyJWT, rateLimiter, sanitization, responseHandler +├── routes/v1/ # API route definitions +├── validation/ # Joi input validation schemas +└── repositories/ # Data access layer +``` + +### Frontend Structure +``` +client/src/ +├── Components/ # Reusable UI components +├── Pages/ # Page components (Auth, Uptime, Infrastructure, Incidents, etc.) +├── Features/ # Redux slices (Auth, UI) +├── Hooks/ # Custom React hooks +├── Utils/ # Utilities (NetworkService.js is main API client) +├── Validation/ # Input validation +└── locales/ # i18n translations +``` + +### API +- Base URL: `/api/v1` +- Documentation: `http://localhost:52345/api-docs` (Swagger UI) +- OpenAPI spec: `/server/openapi.json` + +### Key Technologies +- **State Management**: Redux Toolkit + Redux-Persist +- **Data Fetching**: SWR + Axios +- **Database**: MongoDB with Mongoose ODM +- **Queue/Cache**: Redis + BullMQ + Pulse (cron scheduling) +- **i18n**: i18next + react-i18next (translations via PoEditor) + +## Code Conventions + +### Internationalization +All user-facing strings must use the translation function: +```javascript +t('your.key') // Never hardcode UI strings +``` + +### Branching +- Always branch from `develop` (not master) +- Use descriptive names: `feat/add-alerts`, `fix/login-error` +- PRs target `develop` branch + +### Formatting +- **Client**: Prettier with `printWidth: 90`, tabs, double quotes +- **Server**: Prettier with `printWidth: 150`, tabs, double quotes +- Both use ESLint with strict settings + +### Testing +Server tests use Mocha + Chai + Sinon: +```bash +npm test # Run all tests with coverage +npm test -- --grep "pattern" # Run specific tests +``` +Test files: `server/tests/**/*.test.js` + +## Database Models + +Key Mongoose models in `/server/src/db/models/`: +- **Monitor** - Monitoring configuration (website, infrastructure, port, etc.) +- **Check** - Individual monitoring check results +- **Incident** - Downtime incidents +- **User** - User accounts +- **Team** - Team/workspace management +- **StatusPage** - Public status pages +- **Notification** - Alert configuration (email, Discord, Slack, webhooks) +- **MaintenanceWindow** - Scheduled maintenance periods +- **AppSettings** - Global application settings diff --git a/client/package-lock.json b/client/package-lock.json index e917619ae..7f5397b7f 100644 --- a/client/package-lock.json +++ b/client/package-lock.json @@ -12,7 +12,6 @@ "@emotion/styled": "^11.13.0", "@hello-pangea/dnd": "^18.0.0", "@hookform/resolvers": "5.2.2", - "@mui/icons-material": "6.4.11", "@mui/lab": "6.0.0-dev.240424162023-9968b4889d", "@mui/material": "6.4.11", "@mui/x-charts": "^7.5.1", @@ -25,6 +24,7 @@ "human-interval": "2.0.1", "i18next": "25.4.2", "joi": "17.13.3", + "lucide-react": "^0.562.0", "mui-color-input": "^6.0.0", "pretty-ms": "9.3.0", "react": "18.3.1", @@ -1189,32 +1189,6 @@ "url": "https://opencollective.com/mui-org" } }, - "node_modules/@mui/icons-material": { - "version": "6.4.11", - "resolved": "https://registry.npmjs.org/@mui/icons-material/-/icons-material-6.4.11.tgz", - "integrity": "sha512-+jjJGIrB1awNbMv4ZVPPdN/p7O1UKFZ+xqRvNIQ8B1KnlID5hPMPBLM6UUbRF4bu3UDCbu79rn9Nye5LGNzmeA==", - "license": "MIT", - "dependencies": { - "@babel/runtime": "^7.26.0" - }, - "engines": { - "node": ">=14.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/mui-org" - }, - "peerDependencies": { - "@mui/material": "^6.4.11", - "@types/react": "^17.0.0 || ^18.0.0 || ^19.0.0", - "react": "^17.0.0 || ^18.0.0 || ^19.0.0" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - } - } - }, "node_modules/@mui/lab": { "version": "6.0.0-dev.240424162023-9968b4889d", "resolved": "https://registry.npmjs.org/@mui/lab/-/lab-6.0.0-dev.240424162023-9968b4889d.tgz", @@ -2050,9 +2024,9 @@ } }, "node_modules/@remix-run/router": { - "version": "1.23.0", - "resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.23.0.tgz", - "integrity": "sha512-O3rHJzAQKamUz1fvE0Qaw0xSFqsA/yafi2iqeE0pvdFtCO1viYx8QL6f3Ln/aCCTLxs68SLf0KPM9eSeM8yBnA==", + "version": "1.23.2", + "resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.23.2.tgz", + "integrity": "sha512-Ic6m2U/rMjTkhERIa/0ZtXJP17QUi2CbWE7cqx4J58M8aA3QTfW+2UlQ4psvTX9IO1RfNVhK3pcpdjej7L+t2w==", "license": "MIT", "engines": { "node": ">=14.0.0" @@ -5297,9 +5271,9 @@ "license": "MIT" }, "node_modules/js-yaml": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", - "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz", + "integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==", "license": "MIT", "dependencies": { "argparse": "^2.0.1" @@ -5464,6 +5438,15 @@ "yallist": "^3.0.2" } }, + "node_modules/lucide-react": { + "version": "0.562.0", + "resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-0.562.0.tgz", + "integrity": "sha512-82hOAu7y0dbVuFfmO4bYF1XEwYk/mEbM5E+b1jgci/udUBEE/R7LF5Ip0CCEmXe8AybRM8L+04eP+LGZeDvkiw==", + "license": "ISC", + "peerDependencies": { + "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" + } + }, "node_modules/math-intrinsics": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", @@ -6129,12 +6112,12 @@ } }, "node_modules/react-router": { - "version": "6.30.1", - "resolved": "https://registry.npmjs.org/react-router/-/react-router-6.30.1.tgz", - "integrity": "sha512-X1m21aEmxGXqENEPG3T6u0Th7g0aS4ZmoNynhbs+Cn+q+QGTLt+d5IQ2bHAXKzKcxGJjxACpVbnYQSCRcfxHlQ==", + "version": "6.30.3", + "resolved": "https://registry.npmjs.org/react-router/-/react-router-6.30.3.tgz", + "integrity": "sha512-XRnlbKMTmktBkjCLE8/XcZFlnHvr2Ltdr1eJX4idL55/9BbORzyZEaIkBFDhFGCEWBBItsVrDxwx3gnisMitdw==", "license": "MIT", "dependencies": { - "@remix-run/router": "1.23.0" + "@remix-run/router": "1.23.2" }, "engines": { "node": ">=14.0.0" @@ -6144,13 +6127,13 @@ } }, "node_modules/react-router-dom": { - "version": "6.30.1", - "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.30.1.tgz", - "integrity": "sha512-llKsgOkZdbPU1Eg3zK8lCn+sjD9wMRZZPuzmdWWX5SUs8OFkN5HnFVC0u5KMeMaC9aoancFI/KoLuKPqN+hxHw==", + "version": "6.30.3", + "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.30.3.tgz", + "integrity": "sha512-pxPcv1AczD4vso7G4Z3TKcvlxK7g7TNt3/FNGMhfqyntocvYKj+GCatfigGDjbLozC4baguJ0ReCigoDJXb0ag==", "license": "MIT", "dependencies": { - "@remix-run/router": "1.23.0", - "react-router": "6.30.1" + "@remix-run/router": "1.23.2", + "react-router": "6.30.3" }, "engines": { "node": ">=14.0.0" diff --git a/client/package.json b/client/package.json index 376671942..50fafb35c 100644 --- a/client/package.json +++ b/client/package.json @@ -17,7 +17,6 @@ "@emotion/styled": "^11.13.0", "@hello-pangea/dnd": "^18.0.0", "@hookform/resolvers": "5.2.2", - "@mui/icons-material": "6.4.11", "@mui/lab": "6.0.0-dev.240424162023-9968b4889d", "@mui/material": "6.4.11", "@mui/x-charts": "^7.5.1", @@ -30,6 +29,7 @@ "human-interval": "2.0.1", "i18next": "25.4.2", "joi": "17.13.3", + "lucide-react": "^0.562.0", "mui-color-input": "^6.0.0", "pretty-ms": "9.3.0", "react": "18.3.1", diff --git a/client/src/Components/LanguageSelector.jsx b/client/src/Components/LanguageSelector.jsx index 9b46204e3..fdda73f4a 100644 --- a/client/src/Components/LanguageSelector.jsx +++ b/client/src/Components/LanguageSelector.jsx @@ -16,7 +16,7 @@ const langMap = { const LanguageSelector = () => { const { i18n } = useTranslation(); const theme = useTheme(); - const { language } = useSelector((state) => state.ui); + const { language = "en" } = useSelector((state) => state.ui); const dispatch = useDispatch(); const handleChange = (event) => { const newLang = event.target.value; diff --git a/client/src/Components/v1/ActionsMenu/index.jsx b/client/src/Components/v1/ActionsMenu/index.jsx index 5cd0dfa5b..ea0d029b8 100644 --- a/client/src/Components/v1/ActionsMenu/index.jsx +++ b/client/src/Components/v1/ActionsMenu/index.jsx @@ -2,7 +2,7 @@ import IconButton from "@mui/material/IconButton"; import Menu from "@mui/material/Menu"; import MenuItem from "@mui/material/MenuItem"; -import Settings from "../../../assets/icons/settings-bold.svg?react"; +import Icon from "../Icon"; import Dialog from "../Dialog/index.jsx"; // Utils @@ -32,7 +32,6 @@ const ActionsMenu = ({ event.preventDefault(); event.stopPropagation(); let monitor = { id: actions.id }; - console.log(monitor); await deleteMonitor({ monitor }); updateRowCallback(); }; @@ -84,7 +83,10 @@ const ActionsMenu = ({ }, }} > - + , - error: , - warning: , + info: ( + + ), + error: ( + + ), + warning: ( + + ), }; /** @@ -97,10 +109,9 @@ const Alert = ({ variant, title, body, isToast, hasIcon = true, onClick }) => { }, }} > - )} diff --git a/client/src/Components/v1/ArrowLeft/index.jsx b/client/src/Components/v1/ArrowLeft/index.jsx index a327d6bb7..e18a7f2d5 100644 --- a/client/src/Components/v1/ArrowLeft/index.jsx +++ b/client/src/Components/v1/ArrowLeft/index.jsx @@ -1,27 +1,28 @@ -import LeftArrow from "../../../assets/icons/left-arrow.svg?react"; -import LeftArrowDouble from "../../../assets/icons/left-arrow-double.svg?react"; -import LeftArrowLong from "../../../assets/icons/left-arrow-long.svg?react"; +import Icon from "../Icon"; import PropTypes from "prop-types"; const ArrowLeft = ({ type, color = "#667085", ...props }) => { if (type === "double") { return ( - ); } else if (type === "long") { return ( - ); } else { return ( - ); diff --git a/client/src/Components/v1/ArrowRight/index.jsx b/client/src/Components/v1/ArrowRight/index.jsx index 08a2639b0..3ae64a580 100644 --- a/client/src/Components/v1/ArrowRight/index.jsx +++ b/client/src/Components/v1/ArrowRight/index.jsx @@ -1,19 +1,20 @@ -import RightArrow from "../../../assets/icons/right-arrow.svg?react"; -import RightArrowDouble from "../../../assets/icons/right-arrow-double.svg?react"; +import Icon from "../Icon"; import PropTypes from "prop-types"; const ArrowRight = ({ type, color = "#667085", ...props }) => { if (type === "double") { return ( - ); } else { return ( - ); diff --git a/client/src/Components/v1/Check/Check.jsx b/client/src/Components/v1/Check/Check.jsx index 53971316b..cc3749fda 100644 --- a/client/src/Components/v1/Check/Check.jsx +++ b/client/src/Components/v1/Check/Check.jsx @@ -1,7 +1,6 @@ import "./check.css"; import PropTypes from "prop-types"; -import CheckGrey from "../../../assets/icons/check.svg?react"; -import CheckOutlined from "../../../assets/icons/check-outlined.svg?react"; +import Icon from "../Icon"; import { Box, Stack, Typography } from "@mui/material"; import { useTheme } from "@emotion/react"; @@ -35,16 +34,16 @@ const Check = ({ text, noHighlightText, variant = "info", outlined = false }) => alignItems="center" > {outlined ? ( - + ) : ( - path": { fill: colors[variant] }, - }} - > - - + )} { aria-label="Menu button" onClick={toggleDrawer(true)} > - + { }} > - + diff --git a/client/src/Components/v1/FilterHeader/index.jsx b/client/src/Components/v1/FilterHeader/index.jsx index 36dd04081..de2c7f0e9 100644 --- a/client/src/Components/v1/FilterHeader/index.jsx +++ b/client/src/Components/v1/FilterHeader/index.jsx @@ -1,7 +1,7 @@ import { Checkbox, FormControl, ListItemText, MenuItem, Select } from "@mui/material"; import { useTheme } from "@emotion/react"; import PropTypes from "prop-types"; -import AddCircleOutlineIcon from "@mui/icons-material/AddCircleOutline"; +import Icon from "../Icon"; /** * A reusable filter header component that displays a dropdown menu with selectable options. @@ -29,9 +29,10 @@ const FilterHeader = ({ header, options, value, onChange, multiple = true }) => { - setLogLevel(e.target.value); - }} + onChange={handleLogLevelChange} /> - - - {logs - ?.filter((log) => { - if (logLevel === "all") return true; - return log.level === logLevel; - }) - .reverse() - .map((log, idx) => formatLog(theme, log, idx))} - - + /> + + {filteredLogs?.length > 0 && ( + + )} ); }; diff --git a/client/src/Pages/Maintenance/CreateMaintenance/Components/MonitorList/index.jsx b/client/src/Pages/Maintenance/CreateMaintenance/Components/MonitorList/index.jsx index c70912582..2bf7a991f 100644 --- a/client/src/Pages/Maintenance/CreateMaintenance/Components/MonitorList/index.jsx +++ b/client/src/Pages/Maintenance/CreateMaintenance/Components/MonitorList/index.jsx @@ -1,6 +1,6 @@ // Components import { Stack, Typography } from "@mui/material"; -import DeleteIcon from "@mui/icons-material/Delete"; +import Icon from "@/Components/v1/Icon"; import { useTheme } from "@emotion/react"; import PropTypes from "prop-types"; @@ -14,8 +14,10 @@ const MonitorListItem = ({ monitor, onDelete }) => { width="100%" > {monitor.name} - onDelete(monitor)} /> diff --git a/client/src/Pages/Maintenance/CreateMaintenance/index.jsx b/client/src/Pages/Maintenance/CreateMaintenance/index.jsx index 759679a2d..3e8090325 100644 --- a/client/src/Pages/Maintenance/CreateMaintenance/index.jsx +++ b/client/src/Pages/Maintenance/CreateMaintenance/index.jsx @@ -16,7 +16,7 @@ import useMaintenanceActions from "./hooks/useMaintenanceActions.jsx"; import TextInput from "@/Components/v1/Inputs/TextInput/index.jsx"; import Breadcrumbs from "@/Components/v1/Breadcrumbs/index.jsx"; -import CalendarIcon from "@/assets/icons/calendar.svg?react"; +import Icon from "@/Components/v1/Icon"; import "./index.css"; import Search from "@/Components/v1/Inputs/Search/index.jsx"; import { logger } from "@/Utils/Logger.js"; @@ -217,7 +217,14 @@ const CreateMaintenance = () => { disablePast disableHighlightToday value={form.startDate} - slots={{ openPickerIcon: () => }} + slots={{ + openPickerIcon: () => ( + + ), + }} slotProps={{ switchViewButton: { sx: { display: "none" } }, nextIconButton: { sx: { ml: theme.spacing(2) } }, diff --git a/client/src/Pages/Maintenance/MaintenanceTable/ActionsMenu/index.jsx b/client/src/Pages/Maintenance/MaintenanceTable/ActionsMenu/index.jsx index 38a3d8e64..09c69dd98 100644 --- a/client/src/Pages/Maintenance/MaintenanceTable/ActionsMenu/index.jsx +++ b/client/src/Pages/Maintenance/MaintenanceTable/ActionsMenu/index.jsx @@ -4,7 +4,7 @@ import { useNavigate } from "react-router-dom"; import { useSelector } from "react-redux"; import { IconButton, Menu, MenuItem } from "@mui/material"; import { logger } from "@/Utils/Logger.js"; -import Settings from "@/assets/icons/settings-bold.svg?react"; +import Icon from "@/Components/v1/Icon"; import PropTypes from "prop-types"; import { networkService } from "../../../../main.jsx"; import { createToast } from "@/Utils/toastUtils.jsx"; @@ -98,7 +98,10 @@ const ActionsMenu = ({ /* isAdmin, */ maintenanceWindow, updateCallback }) => { }, }} > - + {sort.order === "asc" ? ( - + ) : ( - + )} @@ -89,9 +94,15 @@ const MaintenanceTable = ({ }} > {sort.order === "asc" ? ( - + ) : ( - + )} diff --git a/client/src/Pages/Notifications/components/ActionMenu.jsx b/client/src/Pages/Notifications/components/ActionMenu.jsx index d57ad931f..52516a737 100644 --- a/client/src/Pages/Notifications/components/ActionMenu.jsx +++ b/client/src/Pages/Notifications/components/ActionMenu.jsx @@ -1,7 +1,7 @@ // Components import Menu from "@mui/material/Menu"; import IconButton from "@mui/material/IconButton"; -import SettingsOutlinedIcon from "@mui/icons-material/SettingsOutlined"; +import Icon from "@/Components/v1/Icon"; import MenuItem from "@mui/material/MenuItem"; // Utils @@ -49,7 +49,10 @@ const ActionMenu = ({ notification, onDelete }) => { onClick={handleClick} onMouseDown={(e) => e.stopPropagation()} > - + { const handleRemove = async (event) => { event.preventDefault(); - const TEMP_MONITOR = { id: monitor._id }; - await deleteMonitor({ monitor: TEMP_MONITOR, redirect: "/pagespeed" }); + await deleteMonitor({ monitor: { id: monitorId }, redirect: "/pagespeed" }); }; const isBusy = isLoading || isCreating || isDeleting || isUpdating || isPausing; @@ -314,12 +312,18 @@ const PageSpeedSetup = () => { > {monitor?.isActive ? ( <> - + {t("pause")} ) : ( <> - + {t("resume")} )} diff --git a/client/src/Pages/PageSpeed/Details/Components/Charts/AreaChartLegend.jsx b/client/src/Pages/PageSpeed/Details/Components/Charts/AreaChartLegend.jsx index 113e4d618..525e4d0d2 100644 --- a/client/src/Pages/PageSpeed/Details/Components/Charts/AreaChartLegend.jsx +++ b/client/src/Pages/PageSpeed/Details/Components/Charts/AreaChartLegend.jsx @@ -1,6 +1,6 @@ import { Box, Typography, Divider } from "@mui/material"; import Checkbox from "@/Components/v1/Inputs/Checkbox/index.jsx"; -import MetricsIcon from "@/assets/icons/ruler-icon.svg?react"; +import Icon from "@/Components/v1/Icon"; import LegendBox from "@/Components/v1/Charts/LegendBox/index.jsx"; import { useTranslation } from "react-i18next"; import { useTheme } from "@emotion/react"; @@ -10,7 +10,12 @@ const AreaChartLegend = ({ metrics, handleMetrics }) => { const { t } = useTranslation(); return ( } + icon={ + + } header="Metrics" > diff --git a/client/src/Pages/PageSpeed/Details/Components/Charts/PieChartLegend.jsx b/client/src/Pages/PageSpeed/Details/Components/Charts/PieChartLegend.jsx index 43e2371b4..5cfdad608 100644 --- a/client/src/Pages/PageSpeed/Details/Components/Charts/PieChartLegend.jsx +++ b/client/src/Pages/PageSpeed/Details/Components/Charts/PieChartLegend.jsx @@ -1,7 +1,7 @@ import { Stack, Box, Typography } from "@mui/material"; import { useTheme } from "@emotion/react"; import LegendBox from "@/Components/v1/Charts/LegendBox/index.jsx"; -import SpeedometerIcon from "@/assets/icons/speedometer-icon.svg?react"; +import Icon from "@/Components/v1/Icon"; import PropTypes from "prop-types"; const PieChartLegend = ({ audits }) => { @@ -9,7 +9,12 @@ const PieChartLegend = ({ audits }) => { return ( } + icon={ + + } header="Performance metrics" sx={{ flex: 1 }} > diff --git a/client/src/Pages/PageSpeed/Details/Components/PageSpeedAreaChart/index.jsx b/client/src/Pages/PageSpeed/Details/Components/PageSpeedAreaChart/index.jsx index aa88d57e5..9020ddd6d 100644 --- a/client/src/Pages/PageSpeed/Details/Components/PageSpeedAreaChart/index.jsx +++ b/client/src/Pages/PageSpeed/Details/Components/PageSpeedAreaChart/index.jsx @@ -2,7 +2,7 @@ import ChartBox from "@/Components/v1/Charts/ChartBox/index.jsx"; import AreaChart from "../Charts/AreaChart.jsx"; import AreaChartLegend from "../Charts/AreaChartLegend.jsx"; import SkeletonLayout from "./skeleton.jsx"; -import ScoreIcon from "@/assets/icons/monitor-graph-line.svg?react"; +import Icon from "@/Components/v1/Icon"; import { Stack } from "@mui/material"; import PropTypes from "prop-types"; @@ -24,7 +24,12 @@ const PageSpeedAreaChart = ({ shouldRender, monitor, metrics, handleMetrics }) = > } + icon={ + + } header="Score history" height="100%" borderRadiusRight={16} diff --git a/client/src/Pages/PageSpeed/Details/Components/PageSpeedStatusBoxes/index.jsx b/client/src/Pages/PageSpeed/Details/Components/PageSpeedStatusBoxes/index.jsx index 493d1ece6..872b1e293 100644 --- a/client/src/Pages/PageSpeed/Details/Components/PageSpeedStatusBoxes/index.jsx +++ b/client/src/Pages/PageSpeed/Details/Components/PageSpeedStatusBoxes/index.jsx @@ -4,9 +4,21 @@ import { Typography } from "@mui/material"; import { getHumanReadableDuration } from "../../../../../Utils/timeUtils.js"; import { useTranslation } from "react-i18next"; -const PageSpeedStatusBoxes = ({ shouldRender, monitor }) => { - const uptimeDuration = getHumanReadableDuration(monitor?.uptimeDuration); - const time = getHumanReadableDuration(monitor?.lastChecked); +const PageSpeedStatusBoxes = ({ shouldRender, monitorStats }) => { + const lastChecked = monitorStats?.lastCheckTimestamp + ? Date.now() - monitorStats.lastCheckTimestamp + : 0; + + // Determine time since last failure + const timeOfLastFailure = monitorStats?.timeOfLastFailure; + const timeSinceLastFailure = + timeOfLastFailure > 0 + ? Date.now() - timeOfLastFailure + : Date.now() - new Date(monitorStats?.createdAt); + + const streakTime = getHumanReadableDuration(timeSinceLastFailure); + + const time = getHumanReadableDuration(lastChecked); const { t } = useTranslation(); @@ -16,7 +28,7 @@ const PageSpeedStatusBoxes = ({ shouldRender, monitor }) => { heading="checks since" subHeading={ <> - {uptimeDuration} + {streakTime} {t("ago")} } diff --git a/client/src/Pages/PageSpeed/Details/Components/PerformanceReport/index.jsx b/client/src/Pages/PageSpeed/Details/Components/PerformanceReport/index.jsx index c2eecaa6a..a2e1b5f96 100644 --- a/client/src/Pages/PageSpeed/Details/Components/PerformanceReport/index.jsx +++ b/client/src/Pages/PageSpeed/Details/Components/PerformanceReport/index.jsx @@ -1,5 +1,5 @@ import ChartBox from "@/Components/v1/Charts/ChartBox/index.jsx"; -import PerformanceIcon from "@/assets/icons/performance-report.svg?react"; +import Icon from "@/Components/v1/Icon"; import PieChart from "../Charts/PieChart.jsx"; import { Typography } from "@mui/material"; import { useTheme } from "@emotion/react"; @@ -17,7 +17,12 @@ const PerformanceReport = ({ shouldRender, audits }) => { return ( } + icon={ + + } header="Performance report" Legend={} borderRadiusRight={16} diff --git a/client/src/Pages/PageSpeed/Details/index.jsx b/client/src/Pages/PageSpeed/Details/index.jsx index df411048a..3190787b3 100644 --- a/client/src/Pages/PageSpeed/Details/index.jsx +++ b/client/src/Pages/PageSpeed/Details/index.jsx @@ -35,7 +35,7 @@ const PageSpeedDetails = () => { }); const [trigger, setTrigger] = useState(false); // Network - const [monitor, isLoading, networkError] = useFetchPageSpeedMonitorById({ + const [monitor, monitorStats, isLoading, networkError] = useFetchPageSpeedMonitorById({ monitorId, dateRange: "day", updateTrigger: trigger, @@ -95,7 +95,7 @@ const PageSpeedDetails = () => { /> { }} > - + { +const MonitorGrid = ({ monitors, shouldRender = true }) => { + if (!shouldRender) return null; + return ( { {monitors?.map((monitor) => ( ))} diff --git a/client/src/Pages/PageSpeed/Monitors/index.jsx b/client/src/Pages/PageSpeed/Monitors/index.jsx index 4530a41e9..f1bfcd0dd 100644 --- a/client/src/Pages/PageSpeed/Monitors/index.jsx +++ b/client/src/Pages/PageSpeed/Monitors/index.jsx @@ -21,6 +21,7 @@ const PageSpeed = () => { const isAdmin = useIsAdmin(); const [ + summary, monitorsWithChecks, monitorsWithChecksCount, monitorsWithChecksIsLoading, diff --git a/client/src/Pages/Settings/index.jsx b/client/src/Pages/Settings/index.jsx index 27cc6bb21..54d6d4209 100644 --- a/client/src/Pages/Settings/index.jsx +++ b/client/src/Pages/Settings/index.jsx @@ -33,7 +33,7 @@ const BREADCRUMBS = [{ name: `Settings`, path: "/settings" }]; const Settings = () => { // Redux state - const { mode, language, timezone, showURL } = useSelector((state) => state.ui); + const { mode, language = "en", timezone, showURL } = useSelector((state) => state.ui); // Local state const [settingsData, setSettingsData] = useState({}); @@ -75,11 +75,6 @@ const Settings = () => { const handleChange = async (e) => { const { name, value, checked } = e.target; - // Special case for showURL until handled properly in the backend - if (name === "showURL") { - dispatch(setShowURL(value)); - return; - } let newValue; if ( name === "systemEmailIgnoreTLS" || @@ -90,6 +85,12 @@ const Settings = () => { ) { newValue = checked; } + + // Ensure showURL is a proper boolean + if (name === "showURL") { + newValue = value === true || value === "true"; + } + // Build next state early const newSettingsData = { ...settingsData, @@ -147,29 +148,22 @@ const Settings = () => { return; } - // Validate - const { error } = settingsValidation.validate(newSettingsData.settings, { - abortEarly: false, - }); - if (!error || error.details.length === 0) { - setErrors({}); - } else { - const newErrors = {}; - error.details.forEach((err) => { - newErrors[err.path[0]] = err.message; - }); - setErrors(newErrors); - } - setSettingsData(newSettingsData); + + // Update Redux immediately for UI feedback + if (name === "showURL") { + dispatch(setShowURL(newValue)); + } }; const handleSave = () => { + // Validate const { error } = settingsValidation.validate(settingsData.settings, { abortEarly: false, }); if (!error || error.details.length === 0) { setErrors({}); + saveSettings(settingsData?.settings); } else { const newErrors = {}; error.details.forEach((err) => { @@ -178,7 +172,6 @@ const Settings = () => { setErrors(newErrors); } - saveSettings(settingsData?.settings); }; return ( diff --git a/client/src/Pages/StatusPage/Create/Components/MonitorList/index.jsx b/client/src/Pages/StatusPage/Create/Components/MonitorList/index.jsx index d2a13b2eb..349571fe8 100644 --- a/client/src/Pages/StatusPage/Create/Components/MonitorList/index.jsx +++ b/client/src/Pages/StatusPage/Create/Components/MonitorList/index.jsx @@ -1,7 +1,6 @@ // Components import { Stack, Typography } from "@mui/material"; -import ReorderRoundedIcon from "@mui/icons-material/ReorderRounded"; -import DeleteIcon from "@mui/icons-material/Delete"; +import Icon from "@/Components/v1/Icon"; // Utils import { DragDropContext, Droppable, Draggable } from "@hello-pangea/dnd"; @@ -28,10 +27,15 @@ const MonitorListItem = ({ justifyContent={"start"} border={`1px solid ${theme.palette.primary.lowContrast}`} > - + {monitor.name} - { onDelete(monitor); }} diff --git a/client/src/Pages/StatusPage/Create/Components/Progress/index.jsx b/client/src/Pages/StatusPage/Create/Components/Progress/index.jsx index 2d9731ea0..594fd9709 100644 --- a/client/src/Pages/StatusPage/Create/Components/Progress/index.jsx +++ b/client/src/Pages/StatusPage/Create/Components/Progress/index.jsx @@ -1,6 +1,6 @@ import { Button, Box } from "@mui/material"; import ProgressUpload from "@/Components/v1/ProgressBars/index.jsx"; -import ImageIcon from "@mui/icons-material/Image"; +import Icon from "@/Components/v1/Icon"; import { useTranslation } from "react-i18next"; import { formatBytes } from "../../../../../Utils/fileUtils.js"; const Progress = ({ isLoading, progressValue, logo, logoType, removeLogo, errors }) => { @@ -8,7 +8,12 @@ const Progress = ({ isLoading, progressValue, logo, logoType, removeLogo, errors if (isLoading) { return ( } + icon={ + + } label={logo?.name} size={formatBytes(logo?.size)} progress={progressValue} diff --git a/client/src/Pages/StatusPage/Status/Components/ControlsHeader/index.jsx b/client/src/Pages/StatusPage/Status/Components/ControlsHeader/index.jsx index 60a4882f5..fe1c4c852 100644 --- a/client/src/Pages/StatusPage/Status/Components/ControlsHeader/index.jsx +++ b/client/src/Pages/StatusPage/Status/Components/ControlsHeader/index.jsx @@ -1,9 +1,8 @@ // Components import { Box, Stack, Typography, Button } from "@mui/material"; import Image from "@/Components/v1/Image/index.jsx"; -import SettingsIcon from "@/assets/icons/settings-bold.svg?react"; +import Icon from "@/Components/v1/Icon"; import ThemeSwitch from "@/Components/v1/ThemeSwitch/index.jsx"; -import ArrowOutwardIcon from "@mui/icons-material/ArrowOutward"; //Utils import { useTheme } from "@mui/material/styles"; import { useNavigate } from "react-router-dom"; @@ -46,7 +45,12 @@ const Controls = ({ url, type }) => { }, }} > - {t("configure")} + {" "} + {t("configure")} @@ -111,7 +115,10 @@ const ControlsHeader = ({ statusPage, isPublic, url, type = "uptime" }) => { }} > {t("publicLink")} - + )} diff --git a/client/src/Pages/StatusPage/Status/Components/StatusBar/index.jsx b/client/src/Pages/StatusPage/Status/Components/StatusBar/index.jsx index 1898ff3d7..7b9460068 100644 --- a/client/src/Pages/StatusPage/Status/Components/StatusBar/index.jsx +++ b/client/src/Pages/StatusPage/Status/Components/StatusBar/index.jsx @@ -1,7 +1,6 @@ // Components import { Stack, Typography } from "@mui/material"; -import CheckCircleIcon from "@mui/icons-material/CheckCircle"; -import ErrorOutlineIcon from "@mui/icons-material/ErrorOutline"; +import Icon from "@/Components/v1/Icon"; // Utils import { useTheme } from "@mui/material/styles"; @@ -10,8 +9,10 @@ import PropTypes from "prop-types"; const getMonitorStatus = (monitors, theme) => { const monitorsStatus = { icon: ( - ), }; @@ -19,8 +20,10 @@ const getMonitorStatus = (monitors, theme) => { monitorsStatus.msg = "All systems operational"; monitorsStatus.color = theme.palette.success.lowContrast; monitorsStatus.icon = ( - ); } diff --git a/client/src/Pages/StatusPage/StatusPages/Components/StatusPagesTable/index.jsx b/client/src/Pages/StatusPage/StatusPages/Components/StatusPagesTable/index.jsx index 1afe25409..9882239bd 100644 --- a/client/src/Pages/StatusPage/StatusPages/Components/StatusPagesTable/index.jsx +++ b/client/src/Pages/StatusPage/StatusPages/Components/StatusPagesTable/index.jsx @@ -2,7 +2,7 @@ import DataTable from "@/Components/v1/Table/index.jsx"; import { useTheme } from "@emotion/react"; import { useNavigate } from "react-router-dom"; import { StatusLabel } from "@/Components/v1/Label/index.jsx"; -import ArrowOutwardIcon from "@mui/icons-material/ArrowOutward"; +import Icon from "@/Components/v1/Icon"; import { Stack, Typography } from "@mui/material"; import { useTranslation } from "react-i18next"; const StatusPagesTable = ({ data }) => { @@ -48,7 +48,12 @@ const StatusPagesTable = ({ data }) => { }} > {content} - {row.isPublished && } + {row.isPublished && ( + + )} ); }, diff --git a/client/src/Pages/Uptime/Create/index.jsx b/client/src/Pages/Uptime/Create/index.jsx index c3421e875..b1460dba6 100644 --- a/client/src/Pages/Uptime/Create/index.jsx +++ b/client/src/Pages/Uptime/Create/index.jsx @@ -28,10 +28,7 @@ import { useEffect, useState } from "react"; import { useTranslation } from "react-i18next"; import { monitorValidation } from "../../../Validation/validation.js"; import { createToast } from "../../../Utils/toastUtils.jsx"; -import { - PauseOutlined as PauseOutlinedIcon, - PlayArrowOutlined as PlayArrowOutlinedIcon, -} from "@mui/icons-material"; +import Icon from "@/Components/v1/Icon"; import { useMonitorUtils } from "../../../Hooks/useMonitorUtils.js"; import { useGetNotificationsByTeamId } from "../../../Hooks/useNotifications.js"; import { useParams } from "react-router-dom"; @@ -107,11 +104,16 @@ const UptimeCreate = ({ isClone = false }) => { // Constants const MS_PER_MINUTE = 60000; const FREQUENCIES = [ + { _id: 0.25, name: t("time.fifteenSeconds") }, + { _id: 0.5, name: t("time.thirtySeconds") }, { _id: 1, name: t("time.oneMinute") }, { _id: 2, name: t("time.twoMinutes") }, { _id: 3, name: t("time.threeMinutes") }, { _id: 4, name: t("time.fourMinutes") }, { _id: 5, name: t("time.fiveMinutes") }, + { _id: 10, name: t("time.tenMinutes") }, + { _id: 15, name: t("time.fifteenMinutes") }, + { _id: 30, name: t("time.thirtyMinutes") }, ]; const GAMELIST = Object.entries(games).map(([key, value]) => ({ @@ -194,7 +196,7 @@ const UptimeCreate = ({ isClone = false }) => { }; } else { form = { - _id: monitor._id, + id: monitor.id, url: monitor.url, name: monitor.name || monitor.url.substring(0, 50), statusWindowSize: monitor.statusWindowSize, @@ -287,7 +289,7 @@ const UptimeCreate = ({ isClone = false }) => { const handleRemove = async (event) => { event.preventDefault(); - const TEMP_MONITOR = { id: monitor._id }; + const TEMP_MONITOR = { id: monitor.id }; await deleteMonitor({ monitor: TEMP_MONITOR, redirect: "/uptime" }); }; @@ -424,7 +426,17 @@ const UptimeCreate = ({ isClone = false }) => { color="secondary" loading={isBusy} startIcon={ - monitor?.isActive ? : + monitor?.isActive ? ( + + ) : ( + + ) } onClick={handlePause} > diff --git a/client/src/Pages/Uptime/Details/Components/ChartBoxes/index.jsx b/client/src/Pages/Uptime/Details/Components/ChartBoxes/index.jsx index 582c7891f..b8496f5ea 100644 --- a/client/src/Pages/Uptime/Details/Components/ChartBoxes/index.jsx +++ b/client/src/Pages/Uptime/Details/Components/ChartBoxes/index.jsx @@ -1,9 +1,7 @@ // Components import { Stack, Typography, Box } from "@mui/material"; import ChartBox from "@/Components/v1/Charts/ChartBox/index.jsx"; -import UptimeIcon from "@/assets/icons/uptime-icon.svg?react"; -import IncidentsIcon from "@/assets/icons/incidents.svg?react"; -import AverageResponseIcon from "@/assets/icons/average-response-icon.svg?react"; +import Icon from "@/Components/v1/Icon"; import UpBarChart from "../Charts/UpBarChart.jsx"; import DownBarChart from "../Charts/DownBarChart.jsx"; import ResponseGaugeChart from "../Charts/ResponseGaugeChart.jsx"; @@ -38,7 +36,12 @@ const ChartBoxes = ({ gap={theme.spacing(8)} > } + icon={ + + } header="Uptime" isEmpty={monitorData?.groupedUpChecks?.length === 0} > @@ -89,7 +92,12 @@ const ChartBoxes = ({ /> } + icon={ + + } header="Incidents" noDataMessage={noIncidentsMessage} isEmpty={monitorData?.groupedDownChecks?.length === 0} @@ -123,7 +131,12 @@ const ChartBoxes = ({ /> } + icon={ + + } header="Average Response Time" > diff --git a/client/src/Pages/Uptime/Details/Components/Charts/ResponseTimeChart.jsx b/client/src/Pages/Uptime/Details/Components/Charts/ResponseTimeChart.jsx index 861b600d4..7e7a940e0 100644 --- a/client/src/Pages/Uptime/Details/Components/Charts/ResponseTimeChart.jsx +++ b/client/src/Pages/Uptime/Details/Components/Charts/ResponseTimeChart.jsx @@ -1,6 +1,6 @@ import ChartBox from "@/Components/v1/Charts/ChartBox/index.jsx"; import MonitorDetailsAreaChart from "@/Components/v1/Charts/MonitorDetailsAreaChart/index.jsx"; -import ResponseTimeIcon from "@/assets/icons/response-time-icon.svg?react"; +import Icon from "@/Components/v1/Icon"; import SkeletonLayout from "./ResponseTimeChartSkeleton.jsx"; import PropTypes from "prop-types"; @@ -11,7 +11,12 @@ const ResponseTImeChart = ({ isLoading = false, groupedChecks = [], dateRange }) return ( } + icon={ + + } header="Response Times" > } + icon={ + + } header="Response Times" height="100%" > diff --git a/client/src/Pages/Uptime/Details/Components/UptimeStatusBoxes/index.jsx b/client/src/Pages/Uptime/Details/Components/UptimeStatusBoxes/index.jsx index 0bfdc1096..252873cf9 100644 --- a/client/src/Pages/Uptime/Details/Components/UptimeStatusBoxes/index.jsx +++ b/client/src/Pages/Uptime/Details/Components/UptimeStatusBoxes/index.jsx @@ -18,7 +18,10 @@ const UptimeStatusBoxes = ({ // Determine time since last failure const timeOfLastFailure = monitorStats?.timeOfLastFailure; - const timeSinceLastFailure = timeOfLastFailure > 0 ? Date.now() - timeOfLastFailure : 0; + const timeSinceLastFailure = + timeOfLastFailure > 0 + ? Date.now() - timeOfLastFailure + : Date.now() - new Date(monitorStats?.createdAt); // Determine time since last check const timeOfLastCheck = monitorStats?.lastCheckTimestamp; diff --git a/client/src/Pages/Uptime/Monitors/Components/Filter/index.jsx b/client/src/Pages/Uptime/Monitors/Components/Filter/index.jsx index b9a6824c1..62ba0be13 100644 --- a/client/src/Pages/Uptime/Monitors/Components/Filter/index.jsx +++ b/client/src/Pages/Uptime/Monitors/Components/Filter/index.jsx @@ -3,7 +3,7 @@ import PropTypes from "prop-types"; import FilterHeader from "@/Components/v1/FilterHeader/index.jsx"; import { useMemo } from "react"; import { Box, Button } from "@mui/material"; -import ClearIcon from "@mui/icons-material/Clear"; +import Icon from "@/Components/v1/Icon"; import { useTranslation } from "react-i18next"; /** @@ -131,7 +131,12 @@ const Filter = ({ color={theme.palette.primary.contrastText} onClick={handleReset} variant="contained" - endIcon={} + endIcon={ + + } sx={{ visibility: isFilterActive ? "visible" : "hidden", }} diff --git a/client/src/Pages/Uptime/Monitors/Components/StatusBoxes/statusBox.jsx b/client/src/Pages/Uptime/Monitors/Components/StatusBoxes/statusBox.jsx index c9015816a..136c3575d 100644 --- a/client/src/Pages/Uptime/Monitors/Components/StatusBoxes/statusBox.jsx +++ b/client/src/Pages/Uptime/Monitors/Components/StatusBoxes/statusBox.jsx @@ -1,9 +1,8 @@ import PropTypes from "prop-types"; import { useTheme } from "@emotion/react"; import { Box, Stack, Typography } from "@mui/material"; -import Arrow from "@/assets/icons/top-right-arrow.svg?react"; +import Icon from "@/Components/v1/Icon"; import Background from "@/assets/Images/background-grid.svg?react"; -import ClockSnooze from "@/assets/icons/clock-snooze.svg?react"; const StatusBox = ({ title, value, status }) => { const theme = useTheme(); @@ -20,21 +19,30 @@ const StatusBox = ({ title, value, status }) => { color = theme.palette.success.lowContrast; icon = ( - + ); } else if (status === "down") { color = theme.palette.error.lowContrast; icon = ( - + ); } else if (status === "paused") { color = theme.palette.warning.lowContrast; icon = ( - + ); } diff --git a/client/src/Pages/Uptime/Monitors/Components/UptimeDataTable/index.jsx b/client/src/Pages/Uptime/Monitors/Components/UptimeDataTable/index.jsx index fe220251d..8c3239dd3 100644 --- a/client/src/Pages/Uptime/Monitors/Components/UptimeDataTable/index.jsx +++ b/client/src/Pages/Uptime/Monitors/Components/UptimeDataTable/index.jsx @@ -1,8 +1,7 @@ // Components import { Box, Stack } from "@mui/material"; import DataTable from "@/Components/v1/Table/index.jsx"; -import ArrowDownwardRoundedIcon from "@mui/icons-material/ArrowDownwardRounded"; -import ArrowUpwardRoundedIcon from "@mui/icons-material/ArrowUpwardRounded"; +import Icon from "@/Components/v1/Icon"; import Host from "@/Components/v1/Host/index.jsx"; import { StatusLabel } from "@/Components/v1/Label/index.jsx"; import BarChart from "@/Components/v1/Charts/BarChart/index.jsx"; @@ -92,9 +91,15 @@ const UptimeDataTable = ({ }} > {sort?.order === "asc" ? ( - + ) : ( - + )} @@ -128,9 +133,15 @@ const UptimeDataTable = ({ }} > {sort?.order === "asc" ? ( - + ) : ( - + )} diff --git a/client/src/Pages/Uptime/Monitors/index.jsx b/client/src/Pages/Uptime/Monitors/index.jsx index fb8d6246b..67019362f 100644 --- a/client/src/Pages/Uptime/Monitors/index.jsx +++ b/client/src/Pages/Uptime/Monitors/index.jsx @@ -27,8 +27,8 @@ import { useSelector, useDispatch } from "react-redux"; import { setRowsPerPage } from "../../../Features/UI/uiSlice.js"; import PropTypes from "prop-types"; import { - useFetchMonitorsWithSummary, useFetchMonitorsWithChecks, + useFetchMonitorsByTeamId, } from "@/Hooks/monitorHooks.js"; import { useTranslation } from "react-i18next"; @@ -103,12 +103,6 @@ const UptimeMonitors = () => { setMonitorUpdateTrigger((prev) => !prev); }, []); - const [monitors, monitorsSummary, monitorsWithSummaryIsLoading, networkError] = - useFetchMonitorsWithSummary({ - types: TYPES, - monitorUpdateTrigger, - }); - const handleReset = () => { setSelectedState(undefined); setSelectedTypes(undefined); @@ -123,16 +117,17 @@ const UptimeMonitors = () => { ]); const activeFilter = [...filterLookup].find(([key]) => key !== undefined); - const field = activeFilter?.[1] || sort?.field; + const field = activeFilter?.[1] || (search ? "name" : sort?.field); const filter = activeFilter?.[0] || search; const effectiveTypes = selectedTypes?.length ? selectedTypes : TYPES; const [ + summary, monitorsWithChecks, monitorsWithChecksCount, monitorsWithChecksIsLoading, - monitorsWithChecksNetworkError, + networkError, ] = useFetchMonitorsWithChecks({ types: effectiveTypes, limit: 25, @@ -144,13 +139,17 @@ const UptimeMonitors = () => { monitorUpdateTrigger, }); + const [monitors, listIsLoading, listNetworkError] = useFetchMonitorsByTeamId({ + type: ["http", "ping", "docker", "port", "game"], + }); + useEffect(() => { if (isSearching) { setPage(undefined); } }, [isSearching]); - const isLoading = monitorsWithSummaryIsLoading || monitorsWithChecksIsLoading; + const isLoading = monitorsWithChecksIsLoading; return ( <> @@ -174,14 +173,14 @@ const UptimeMonitors = () => { /> { /> } + element={} /> } The response from the axios POST request. - */ - async registerUser(form) { - return this.axiosInstance.post(`/auth/register`, form); + async registerUser(user, token) { + return this.axiosInstance.post(`/auth/register`, { user, token }); } /** diff --git a/client/src/Utils/Theme/constants.js b/client/src/Utils/Theme/constants.js index 45217fdeb..2664c6126 100644 --- a/client/src/Utils/Theme/constants.js +++ b/client/src/Utils/Theme/constants.js @@ -1,4 +1,4 @@ -import { lighten, darken } from "@mui/material/styles"; // CAIO_REVIEW +import { lighten } from "@mui/material/styles"; // CAIO_REVIEW const typographyBase = 13; @@ -133,12 +133,6 @@ const newSemanticColors = { light: lighten(newColors.blueBlueWave, 0.2), //CAIO_REVIEW dark: lighten(newColors.blueBlueWave, 0.2), //CAIO_REVIEW }, - darker: { - // CAIO_REVIEW - light: darken(newColors.blueBlueWave, 0.2), // CAIO_REVIEW - dark: darken(newColors.blueBlueWave, 0.2), // CAIO_REVIEW - }, - contrastText: { light: newColors.offWhite, dark: newColors.offWhite, @@ -165,14 +159,6 @@ const newSemanticColors = { light: newColors.blueGray500, dark: newColors.gray500, }, - contrastBorder: { - light: newColors.gray500, - dark: newColors.blueGray600, - }, - contrastBorderDisabled: { - light: newColors.gray100, - dark: newColors.blueGray800, - }, lowContrast: { light: newColors.gray250, dark: newColors.blueGray600, @@ -207,18 +193,6 @@ const newSemanticColors = { light: newColors.blueGray800, dark: newColors.gray100, }, - background: { - light: newColors.gray50, - dark: newColors.offBlack, - }, - border: { - light: newColors.gray500, - dark: newColors.blueGray600, - }, - cardShadow: { - light: "0 0 0 1px rgba(0, 0, 0, 0.04), 0 12px 24px rgba(0, 0, 0, 0.08)", - dark: "0 2px 10px rgba(0, 0, 0, 0.2), 0 0 0 1px rgba(255, 255, 255, 0.04)", - }, }, success: { main: { @@ -234,20 +208,6 @@ const newSemanticColors = { dark: newColors.green200, }, }, - successSecondary: { - main: { - light: undefined, - dark: "#073C2D", - }, - contrastText: { - light: undefined, - dark: "#34D399", - }, - lowContrast: { - light: undefined, - dark: "#094434", - }, - }, warning: { main: { light: newColors.orange700, @@ -316,30 +276,6 @@ const newSemanticColors = { }, }, - map: { - main: { - light: newColors.offWhite, - dark: undefined, - }, - lowContrast: { - light: newColors.gray200, - dark: undefined, - }, - highContrast: { - light: newColors.gray500, - dark: undefined, - }, - }, - chatbot: { - background: { - light: newColors.gray200, - dark: "#112B2B", - }, - textAccent: { - light: "#C084FC", - dark: "#C084FC", - }, - }, alert: { main: { light: newColors.gray200, diff --git a/client/src/Utils/Theme/globalTheme.js b/client/src/Utils/Theme/globalTheme.js index e65baf4c0..58e1a9b63 100644 --- a/client/src/Utils/Theme/globalTheme.js +++ b/client/src/Utils/Theme/globalTheme.js @@ -64,7 +64,7 @@ const baseTheme = (palette) => ({ letterSpacing: "0.5px", textShadow: "0 0 1px rgba(0, 0, 0, 0.15)", "&:hover": { - backgroundColor: darken(theme.palette.accent.darker, 0.05), + backgroundColor: darken(theme.palette.accent.main, 0.25), boxShadow: `0 2px 6px rgba(0, 0, 0, 0.1)`, transition: "all 0.2s ease-in-out", }, @@ -74,7 +74,7 @@ const baseTheme = (palette) => ({ props: (props) => props.color === "accent", style: { "&:hover": { - backgroundColor: theme.palette.accent.darker, + backgroundColor: darken(theme.palette.accent.main, 0.2), }, }, }, diff --git a/client/src/Utils/greeting.jsx b/client/src/Utils/greeting.jsx index d2b7fa033..c4afbf88c 100644 --- a/client/src/Utils/greeting.jsx +++ b/client/src/Utils/greeting.jsx @@ -136,8 +136,8 @@ const Greeting = ({ type = "" }) => { const dispatch = useDispatch(); const { t } = useTranslation(); const { firstName } = useSelector((state) => state.auth.user); - const index = useSelector((state) => state.ui.greeting.index); - const lastUpdate = useSelector((state) => state.ui.greeting.lastUpdate); + const index = useSelector((state) => state.ui.greeting?.index ?? 0); + const lastUpdate = useSelector((state) => state.ui.greeting?.lastUpdate ?? null); const now = new Date(); const hour = now.getHours(); diff --git a/client/src/Validation/validation.js b/client/src/Validation/validation.js index 112bbb349..27d585074 100644 --- a/client/src/Validation/validation.js +++ b/client/src/Validation/validation.js @@ -112,7 +112,7 @@ const loginCredentials = joi.object({ }); const monitorValidation = joi.object({ - _id: joi.string(), + id: joi.string(), userId: joi.string(), teamId: joi.string(), statusWindowSize: joi.number().min(1).max(20).default(5).messages({ @@ -328,6 +328,7 @@ const settingsValidation = joi.object({ systemEmailIgnoreTLS: joi.boolean(), systemEmailRequireTLS: joi.boolean(), systemEmailRejectUnauthorized: joi.boolean(), + showURL: joi.boolean().optional(), globalThresholds: joi .object({ cpu: joi.number().min(1).max(100).allow("").optional(), diff --git a/client/src/assets/icons/alert-icon.svg b/client/src/assets/icons/alert-icon.svg deleted file mode 100644 index 1dc7fc2b7..000000000 --- a/client/src/assets/icons/alert-icon.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/client/src/assets/icons/average-response-icon.svg b/client/src/assets/icons/average-response-icon.svg deleted file mode 100644 index 572e2002f..000000000 --- a/client/src/assets/icons/average-response-icon.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/client/src/assets/icons/bwu-icon.svg b/client/src/assets/icons/bwu-icon.svg deleted file mode 100644 index 80ab50ad9..000000000 --- a/client/src/assets/icons/bwu-icon.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/client/src/assets/icons/calendar-check.svg b/client/src/assets/icons/calendar-check.svg deleted file mode 100644 index 07d96dad9..000000000 --- a/client/src/assets/icons/calendar-check.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/client/src/assets/icons/calendar.svg b/client/src/assets/icons/calendar.svg deleted file mode 100644 index be023a4de..000000000 --- a/client/src/assets/icons/calendar.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/client/src/assets/icons/certificate.svg b/client/src/assets/icons/certificate.svg deleted file mode 100644 index 2bc6c7e74..000000000 --- a/client/src/assets/icons/certificate.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file diff --git a/client/src/assets/icons/changeLog.svg b/client/src/assets/icons/changeLog.svg deleted file mode 100644 index d12f6c10e..000000000 --- a/client/src/assets/icons/changeLog.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/client/src/assets/icons/check-icon.svg b/client/src/assets/icons/check-icon.svg deleted file mode 100644 index 9a2cfac5a..000000000 --- a/client/src/assets/icons/check-icon.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/client/src/assets/icons/check-outlined.svg b/client/src/assets/icons/check-outlined.svg deleted file mode 100644 index 1e779d547..000000000 --- a/client/src/assets/icons/check-outlined.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/client/src/assets/icons/check.svg b/client/src/assets/icons/check.svg deleted file mode 100644 index 357378f40..000000000 --- a/client/src/assets/icons/check.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/client/src/assets/icons/checkbox-filled.svg b/client/src/assets/icons/checkbox-filled.svg deleted file mode 100644 index 8a5be81f0..000000000 --- a/client/src/assets/icons/checkbox-filled.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/client/src/assets/icons/checkbox-green.svg b/client/src/assets/icons/checkbox-green.svg deleted file mode 100644 index dd5676298..000000000 --- a/client/src/assets/icons/checkbox-green.svg +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/client/src/assets/icons/checkbox-outline.svg b/client/src/assets/icons/checkbox-outline.svg deleted file mode 100644 index bf5a7218c..000000000 --- a/client/src/assets/icons/checkbox-outline.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/client/src/assets/icons/checkbox-red.svg b/client/src/assets/icons/checkbox-red.svg deleted file mode 100644 index 3c43a2042..000000000 --- a/client/src/assets/icons/checkbox-red.svg +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/client/src/assets/icons/clock-snooze.svg b/client/src/assets/icons/clock-snooze.svg deleted file mode 100644 index 708e7ba91..000000000 --- a/client/src/assets/icons/clock-snooze.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/client/src/assets/icons/close-icon.svg b/client/src/assets/icons/close-icon.svg deleted file mode 100644 index e1b6b690a..000000000 --- a/client/src/assets/icons/close-icon.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/client/src/assets/icons/cpu-chip.svg b/client/src/assets/icons/cpu-chip.svg deleted file mode 100644 index 5645840b1..000000000 --- a/client/src/assets/icons/cpu-chip.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/client/src/assets/icons/dashboard.svg b/client/src/assets/icons/dashboard.svg deleted file mode 100644 index 8958e90ed..000000000 --- a/client/src/assets/icons/dashboard.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/client/src/assets/icons/discussions.svg b/client/src/assets/icons/discussions.svg deleted file mode 100644 index 293cd51f2..000000000 --- a/client/src/assets/icons/discussions.svg +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/client/src/assets/icons/distributed-uptime.svg b/client/src/assets/icons/distributed-uptime.svg deleted file mode 100644 index e612081e4..000000000 --- a/client/src/assets/icons/distributed-uptime.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/client/src/assets/icons/docs.svg b/client/src/assets/icons/docs.svg deleted file mode 100644 index d36458de2..000000000 --- a/client/src/assets/icons/docs.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/client/src/assets/icons/dots-vertical.svg b/client/src/assets/icons/dots-vertical.svg deleted file mode 100644 index e720066c4..000000000 --- a/client/src/assets/icons/dots-vertical.svg +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/client/src/assets/icons/down-arrow.svg b/client/src/assets/icons/down-arrow.svg deleted file mode 100644 index 59b4b6bc5..000000000 --- a/client/src/assets/icons/down-arrow.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/client/src/assets/icons/edit.svg b/client/src/assets/icons/edit.svg deleted file mode 100644 index be2c78408..000000000 --- a/client/src/assets/icons/edit.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/client/src/assets/icons/email.svg b/client/src/assets/icons/email.svg deleted file mode 100644 index 01f55e961..000000000 --- a/client/src/assets/icons/email.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/client/src/assets/icons/folder.svg b/client/src/assets/icons/folder.svg deleted file mode 100644 index 15941e5b5..000000000 --- a/client/src/assets/icons/folder.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/client/src/assets/icons/groups.svg b/client/src/assets/icons/groups.svg deleted file mode 100644 index fa2cae03c..000000000 --- a/client/src/assets/icons/groups.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/client/src/assets/icons/history-icon.svg b/client/src/assets/icons/history-icon.svg deleted file mode 100644 index 7343455ec..000000000 --- a/client/src/assets/icons/history-icon.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/client/src/assets/icons/incidents.svg b/client/src/assets/icons/incidents.svg deleted file mode 100644 index ffe04d09f..000000000 --- a/client/src/assets/icons/incidents.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/client/src/assets/icons/integrations.svg b/client/src/assets/icons/integrations.svg deleted file mode 100644 index 50e817f00..000000000 --- a/client/src/assets/icons/integrations.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/client/src/assets/icons/interval-check.svg b/client/src/assets/icons/interval-check.svg deleted file mode 100644 index 923475c8b..000000000 --- a/client/src/assets/icons/interval-check.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/client/src/assets/icons/jupiter_ag_logo.svg b/client/src/assets/icons/jupiter_ag_logo.svg deleted file mode 100644 index b344961c8..000000000 --- a/client/src/assets/icons/jupiter_ag_logo.svg +++ /dev/null @@ -1,52 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/client/src/assets/icons/jupiter_logo_banner_dark.svg b/client/src/assets/icons/jupiter_logo_banner_dark.svg deleted file mode 100644 index 3d3e23b14..000000000 --- a/client/src/assets/icons/jupiter_logo_banner_dark.svg +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/client/src/assets/icons/jupiter_logo_banner_light.svg b/client/src/assets/icons/jupiter_logo_banner_light.svg deleted file mode 100644 index 4744e0bcb..000000000 --- a/client/src/assets/icons/jupiter_logo_banner_light.svg +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/client/src/assets/icons/key.svg b/client/src/assets/icons/key.svg deleted file mode 100644 index 5db8d5f16..000000000 --- a/client/src/assets/icons/key.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/client/src/assets/icons/left-arrow-double.svg b/client/src/assets/icons/left-arrow-double.svg deleted file mode 100644 index 4cb2a5186..000000000 --- a/client/src/assets/icons/left-arrow-double.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - \ No newline at end of file diff --git a/client/src/assets/icons/left-arrow-long.svg b/client/src/assets/icons/left-arrow-long.svg deleted file mode 100644 index 56a774730..000000000 --- a/client/src/assets/icons/left-arrow-long.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - \ No newline at end of file diff --git a/client/src/assets/icons/left-arrow.svg b/client/src/assets/icons/left-arrow.svg deleted file mode 100644 index 649d1681c..000000000 --- a/client/src/assets/icons/left-arrow.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - \ No newline at end of file diff --git a/client/src/assets/icons/lock.svg b/client/src/assets/icons/lock.svg deleted file mode 100644 index a87535d54..000000000 --- a/client/src/assets/icons/lock.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/client/src/assets/icons/logout.svg b/client/src/assets/icons/logout.svg deleted file mode 100644 index 3f3b69c49..000000000 --- a/client/src/assets/icons/logout.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/client/src/assets/icons/logs.svg b/client/src/assets/icons/logs.svg deleted file mode 100644 index 556c3ba33..000000000 --- a/client/src/assets/icons/logs.svg +++ /dev/null @@ -1,5 +0,0 @@ - - - \ No newline at end of file diff --git a/client/src/assets/icons/mail.svg b/client/src/assets/icons/mail.svg deleted file mode 100644 index 75c22b111..000000000 --- a/client/src/assets/icons/mail.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/client/src/assets/icons/maintenance.svg b/client/src/assets/icons/maintenance.svg deleted file mode 100644 index 9486f6086..000000000 --- a/client/src/assets/icons/maintenance.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/client/src/assets/icons/monitor-graph-line.svg b/client/src/assets/icons/monitor-graph-line.svg deleted file mode 100644 index 86049eb9e..000000000 --- a/client/src/assets/icons/monitor-graph-line.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/client/src/assets/icons/monitors.svg b/client/src/assets/icons/monitors.svg deleted file mode 100644 index f40f36433..000000000 --- a/client/src/assets/icons/monitors.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/client/src/assets/icons/notifications.svg b/client/src/assets/icons/notifications.svg deleted file mode 100644 index c09ac5746..000000000 --- a/client/src/assets/icons/notifications.svg +++ /dev/null @@ -1,5 +0,0 @@ - - - \ No newline at end of file diff --git a/client/src/assets/icons/open-in-new-page.svg b/client/src/assets/icons/open-in-new-page.svg deleted file mode 100644 index 70599f390..000000000 --- a/client/src/assets/icons/open-in-new-page.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/client/src/assets/icons/page-speed.svg b/client/src/assets/icons/page-speed.svg deleted file mode 100644 index 30a1c8a53..000000000 --- a/client/src/assets/icons/page-speed.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/client/src/assets/icons/pause-icon.svg b/client/src/assets/icons/pause-icon.svg deleted file mode 100644 index c73abfc1d..000000000 --- a/client/src/assets/icons/pause-icon.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/client/src/assets/icons/performance-report.svg b/client/src/assets/icons/performance-report.svg deleted file mode 100644 index 8b7073ac3..000000000 --- a/client/src/assets/icons/performance-report.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/client/src/assets/icons/radio-checked.svg b/client/src/assets/icons/radio-checked.svg deleted file mode 100644 index 1c584b79a..000000000 --- a/client/src/assets/icons/radio-checked.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/client/src/assets/icons/response-time-icon.svg b/client/src/assets/icons/response-time-icon.svg deleted file mode 100644 index db5b2af38..000000000 --- a/client/src/assets/icons/response-time-icon.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/client/src/assets/icons/resume-icon.svg b/client/src/assets/icons/resume-icon.svg deleted file mode 100644 index 1da787081..000000000 --- a/client/src/assets/icons/resume-icon.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/client/src/assets/icons/right-arrow-double.svg b/client/src/assets/icons/right-arrow-double.svg deleted file mode 100644 index 6ad4882ad..000000000 --- a/client/src/assets/icons/right-arrow-double.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - \ No newline at end of file diff --git a/client/src/assets/icons/right-arrow.svg b/client/src/assets/icons/right-arrow.svg deleted file mode 100644 index 77d022798..000000000 --- a/client/src/assets/icons/right-arrow.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - \ No newline at end of file diff --git a/client/src/assets/icons/ruler-icon.svg b/client/src/assets/icons/ruler-icon.svg deleted file mode 100644 index 7266d2876..000000000 --- a/client/src/assets/icons/ruler-icon.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/client/src/assets/icons/search.svg b/client/src/assets/icons/search.svg deleted file mode 100644 index a1bc74224..000000000 --- a/client/src/assets/icons/search.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/client/src/assets/icons/selector-vertical.svg b/client/src/assets/icons/selector-vertical.svg deleted file mode 100644 index 29d9a4998..000000000 --- a/client/src/assets/icons/selector-vertical.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/client/src/assets/icons/settings-bold.svg b/client/src/assets/icons/settings-bold.svg deleted file mode 100644 index d8057286c..000000000 --- a/client/src/assets/icons/settings-bold.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/client/src/assets/icons/settings.svg b/client/src/assets/icons/settings.svg deleted file mode 100644 index eb86f1d19..000000000 --- a/client/src/assets/icons/settings.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/client/src/assets/icons/solana_logo.svg b/client/src/assets/icons/solana_logo.svg deleted file mode 100644 index bd349af26..000000000 --- a/client/src/assets/icons/solana_logo.svg +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - - - - - - - - - - - - diff --git a/client/src/assets/icons/solana_logo_banner.svg b/client/src/assets/icons/solana_logo_banner.svg deleted file mode 100644 index 08ec87cb1..000000000 --- a/client/src/assets/icons/solana_logo_banner.svg +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/client/src/assets/icons/spedometer-icon.svg b/client/src/assets/icons/spedometer-icon.svg deleted file mode 100644 index 19b13f44e..000000000 --- a/client/src/assets/icons/spedometer-icon.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/client/src/assets/icons/speedometer-icon.svg b/client/src/assets/icons/speedometer-icon.svg deleted file mode 100644 index 19b13f44e..000000000 --- a/client/src/assets/icons/speedometer-icon.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/client/src/assets/icons/status-pages.svg b/client/src/assets/icons/status-pages.svg deleted file mode 100644 index 97cea88fb..000000000 --- a/client/src/assets/icons/status-pages.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/client/src/assets/icons/support.svg b/client/src/assets/icons/support.svg deleted file mode 100644 index 7de16379a..000000000 --- a/client/src/assets/icons/support.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/client/src/assets/icons/top-right-arrow.svg b/client/src/assets/icons/top-right-arrow.svg deleted file mode 100644 index d569cdd7e..000000000 --- a/client/src/assets/icons/top-right-arrow.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/client/src/assets/icons/trash-bin.svg b/client/src/assets/icons/trash-bin.svg deleted file mode 100644 index 83bca0c6f..000000000 --- a/client/src/assets/icons/trash-bin.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/client/src/assets/icons/up-arrow.svg b/client/src/assets/icons/up-arrow.svg deleted file mode 100644 index 0f8f3bc34..000000000 --- a/client/src/assets/icons/up-arrow.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/client/src/assets/icons/uptime-icon.svg b/client/src/assets/icons/uptime-icon.svg deleted file mode 100644 index 55706ae71..000000000 --- a/client/src/assets/icons/uptime-icon.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/client/src/assets/icons/user-edit.svg b/client/src/assets/icons/user-edit.svg deleted file mode 100644 index cbd1a252f..000000000 --- a/client/src/assets/icons/user-edit.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/client/src/assets/icons/user-two.svg b/client/src/assets/icons/user-two.svg deleted file mode 100644 index 031b22787..000000000 --- a/client/src/assets/icons/user-two.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/client/src/assets/icons/user.svg b/client/src/assets/icons/user.svg deleted file mode 100644 index 231c89d40..000000000 --- a/client/src/assets/icons/user.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/client/src/assets/icons/warning-icon.svg b/client/src/assets/icons/warning-icon.svg deleted file mode 100644 index 468611758..000000000 --- a/client/src/assets/icons/warning-icon.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/client/src/index.css b/client/src/index.css index d58a7e872..b29c17960 100644 --- a/client/src/index.css +++ b/client/src/index.css @@ -4,6 +4,12 @@ box-sizing: border-box; } +html, +body { + background-color: #000000; + overscroll-behavior: none; +} + html { scroll-behavior: smooth; } diff --git a/client/src/locales/en.json b/client/src/locales/en.json index c543eb7e5..9b5ac626f 100644 --- a/client/src/locales/en.json +++ b/client/src/locales/en.json @@ -193,6 +193,8 @@ "total": "Total", "cores": "Cores", "frequency": "Frequency", + "device": "Device", + "mountedOn": "Mounted on", "status": "Status", "cpuPhysical": "CPU (Physical)", "cpuLogical": "CPU (Logical)", @@ -484,7 +486,7 @@ "newPassword": "New password", "enterNewPassword": "Enter your new password", "confirmNewPassword": "Confirm new password", - "passwordRequirements": "New password must contain at least 8 characters and must have at least one uppercase letter, one lowercase letter, one number and one special character.", + "passwordRequirements": "New password must contain at least 8 characters and must have at least one uppercase letter, one lowercase letter, one number and one special character (!?@#$%^&*()-_=+[]{}|;:'\",./\\~`).", "saving": "Saving..." }, "emailSent": "Email sent successfully", @@ -543,7 +545,7 @@ }, "special": { "beginning": "Must contain at least", - "highlighted": "one special character" + "highlighted": "one special character (!?@#$%^&*()-_=+[]{}|;:'\",./\\~`)" }, "number": { "beginning": "Must contain at least", @@ -568,7 +570,7 @@ "uppercase": "Password must contain at least 1 uppercase letter", "lowercase": "Password must contain at least 1 lowercase letter", "number": "Password must contain at least 1 number", - "special": "Password must contain at least 1 special character", + "special": "Password must contain at least 1 special character (!?@#$%^&*()-_=+[]{}|;:'\",./\\~`)", "incorrect": "The password you provided does not match our records" } }, @@ -792,7 +794,16 @@ "error": "Error", "debug": "Debug" } - } + }, + "table": { + "timestamp": "Timestamp", + "level": "Level", + "service": "Service", + "method": "Method", + "message": "Message", + "logs": "logs" + }, + "noLogs": "No logs found" }, "queuePage": { "title": "Queue", @@ -986,6 +997,10 @@ }, "pageSpeedLighthouseAPI": "Use the Lighthouse PageSpeed API to monitor your website", "time": { + "fifteenSeconds": "15 seconds", + "thirtySeconds": "30 seconds", + "fifteenMinutes": "15 minutes", + "thirtyMinutes": "30 minutes", "threeMinutes": "3 minutes", "fiveMinutes": "5 minutes", "tenMinutes": "10 minutes", @@ -995,9 +1010,7 @@ "oneWeek": "1 week", "fourMinutes": "4 minutes", "oneMinute": "1 minute", - "twoMinutes": "2 minutes", - "fifteenSeconds": "15 seconds", - "thirtySeconds": "30 seconds" + "twoMinutes": "2 minutes" }, "general": { "noOptionsFound": "No {{unit}} found" diff --git a/server/jest.config.ts b/server/jest.config.ts index 2bcfcbf21..fd0c87ad7 100644 --- a/server/jest.config.ts +++ b/server/jest.config.ts @@ -8,6 +8,11 @@ const config: Config = { "^.+\\.(t|j)sx?$": ["ts-jest", { useESM: true, tsconfig: "./tsconfig.jest.json" }], }, moduleNameMapper: { + "^@/validation/(.*)\\.js$": "/src/validation/$1.js", + "^@/utils/(AppError)\\.js$": "/src/utils/$1.ts", + "^@/utils/(.*)\\.js$": "/src/utils/$1.js", + "^@/(.*)\\.ts$": "/src/$1.ts", + "^@/(.*)\\.js$": "/src/$1.ts", "^@/(.*)$": "/src/$1", }, testMatch: ["/test/**/*.test.ts"], diff --git a/server/openapi.json b/server/openapi.json index 6cc2e7de0..d56c619bf 100644 --- a/server/openapi.json +++ b/server/openapi.json @@ -21,13 +21,9 @@ "description": "Local Development Server", "variables": { "PORT": { - "description": "API Port", - "enum": ["52345"], "default": "52345" }, "API_PATH": { - "description": "API Base Path", - "enum": ["api/v1"], "default": "api/v1" } } @@ -37,8 +33,6 @@ "description": "Checkmate Demo Server", "variables": { "API_PATH": { - "description": "API Base Path", - "enum": ["api/v1"], "default": "api/v1" } } @@ -88,6 +82,10 @@ { "name": "diagnostic", "description": "System health and performance diagnostics" + }, + { + "name": "incidents", + "description": "Incident management and resolution" } ], "paths": { @@ -164,51 +162,6 @@ } } }, - "/auth/refresh": { - "post": { - "tags": ["auth"], - "summary": "Refresh access token", - "description": "Generate new access token using refresh token", - "parameters": [ - { - "name": "x-refresh-token", - "in": "header", - "description": "Refresh token", - "required": true, - "schema": { - "type": "string" - } - }, - { - "name": "authorization", - "in": "header", - "description": "Bearer token (old access token)", - "required": true, - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "Token refreshed successfully", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/AuthResponse" - } - } - } - }, - "401": { - "$ref": "#/components/responses/Unauthorized" - }, - "500": { - "$ref": "#/components/responses/InternalServerError" - } - } - } - }, "/auth/user/{userId}": { "put": { "tags": ["auth"], @@ -731,28 +684,54 @@ ] } }, - "/monitors/team/summary": { + "/monitors/team/groups": { "get": { "tags": ["monitors"], - "summary": "Get monitors summary", - "description": "Get team monitors with summary statistics", - "parameters": [ - { - "name": "type", - "in": "query", - "description": "Filter by monitor type", - "schema": { - "type": "array", - "items": { - "type": "string", - "enum": ["http", "ping", "pagespeed", "hardware", "docker", "port"] - } - } - } - ], + "summary": "Get monitor groups by team", + "description": "Get all monitor groups for the authenticated user's team", "responses": { "200": { - "description": "Monitor summary retrieved successfully" + "description": "Monitor groups retrieved successfully", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean", + "example": true + }, + "msg": { + "type": "string", + "example": "Monitor groups retrieved successfully" + }, + "data": { + "type": "array", + "items": { + "type": "object", + "properties": { + "_id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "monitors": { + "type": "array", + "items": { + "type": "string" + } + } + } + } + } + } + } + } + } + }, + "401": { + "$ref": "#/components/responses/Unauthorized" }, "500": { "$ref": "#/components/responses/InternalServerError" @@ -992,24 +971,78 @@ ] } }, - "/monitors/stats/{monitorId}": { + "/monitors/pagespeed/details/{monitorId}": { "get": { "tags": ["monitors"], - "summary": "Get monitor statistics", - "description": "Get comprehensive statistics for a monitor", + "summary": "Get PageSpeed monitor details", + "description": "Get detailed PageSpeed monitoring data including performance metrics and Core Web Vitals", "parameters": [ { "name": "monitorId", "in": "path", "required": true, + "description": "The PageSpeed monitor ID", "schema": { "type": "string" } + }, + { + "name": "sortOrder", + "in": "query", + "description": "Sort order for results", + "schema": { + "type": "string", + "enum": ["asc", "desc"], + "default": "desc" + } + }, + { + "name": "limit", + "in": "query", + "description": "Number of results to return", + "schema": { + "type": "integer", + "default": 50 + } } ], "responses": { "200": { - "description": "Monitor statistics retrieved successfully" + "description": "PageSpeed details retrieved successfully", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean", + "example": true + }, + "msg": { + "type": "string", + "example": "PageSpeed details retrieved successfully" + }, + "data": { + "type": "object", + "properties": { + "monitor": { + "$ref": "#/components/schemas/Monitor" + }, + "checks": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Check" + } + } + } + } + } + } + } + } + }, + "401": { + "$ref": "#/components/responses/Unauthorized" }, "404": { "$ref": "#/components/responses/NotFound" @@ -1078,22 +1111,44 @@ ] } }, - "/monitors/export": { + "/monitors/export/json": { "get": { "tags": ["monitors"], - "summary": "Export monitors to CSV", - "description": "Export all monitors to CSV format", + "summary": "Export monitors to JSON", + "description": "Export all monitors to JSON format (admin/superadmin only)", "responses": { "200": { - "description": "CSV file generated successfully", + "description": "JSON file generated successfully", "content": { - "text/csv": { + "application/json": { "schema": { - "type": "string" + "type": "object", + "properties": { + "success": { + "type": "boolean", + "example": true + }, + "msg": { + "type": "string", + "example": "Monitors exported successfully" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Monitor" + } + } + } } } } }, + "401": { + "$ref": "#/components/responses/Unauthorized" + }, + "403": { + "$ref": "#/components/responses/Forbidden" + }, "500": { "$ref": "#/components/responses/InternalServerError" } @@ -1262,6 +1317,39 @@ } }, "/notifications": { + "post": { + "tags": ["notifications"], + "summary": "Create notification", + "description": "Create a new notification integration", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateNotificationRequest" + } + } + } + }, + "responses": { + "201": { + "description": "Notification created successfully" + }, + "422": { + "$ref": "#/components/responses/ValidationError" + }, + "500": { + "$ref": "#/components/responses/InternalServerError" + } + }, + "security": [ + { + "bearerAuth": [] + } + ] + } + }, + "/notifications/team": { "get": { "tags": ["notifications"], "summary": "Get team notifications", @@ -1301,37 +1389,6 @@ "bearerAuth": [] } ] - }, - "post": { - "tags": ["notifications"], - "summary": "Create notification", - "description": "Create a new notification integration", - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/CreateNotificationRequest" - } - } - } - }, - "responses": { - "201": { - "description": "Notification created successfully" - }, - "422": { - "$ref": "#/components/responses/ValidationError" - }, - "500": { - "$ref": "#/components/responses/InternalServerError" - } - }, - "security": [ - { - "bearerAuth": [] - } - ] } }, "/notifications/{id}": { @@ -1722,6 +1779,64 @@ ] } }, + "/auth/users/{userId}/password": { + "put": { + "tags": ["auth"], + "summary": "Update user password by ID", + "description": "Update a specific user's password by ID (superadmin only)", + "parameters": [ + { + "name": "userId", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": ["password"], + "properties": { + "password": { + "type": "string", + "format": "password", + "minLength": 8, + "description": "New password for the user" + } + } + } + } + } + }, + "responses": { + "200": { + "$ref": "#/components/responses/Success" + }, + "404": { + "$ref": "#/components/responses/NotFound" + }, + "403": { + "$ref": "#/components/responses/Forbidden" + }, + "422": { + "$ref": "#/components/responses/ValidationError" + }, + "500": { + "$ref": "#/components/responses/InternalServerError" + } + }, + "security": [ + { + "bearerAuth": [] + } + ] + } + }, "/invite": { "post": { "tags": ["invite"], @@ -2030,6 +2145,21 @@ } } ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "ack": { + "type": "boolean", + "description": "Acknowledgement status" + } + } + } + } + } + }, "responses": { "200": { "$ref": "#/components/responses/Success" @@ -2048,6 +2178,164 @@ ] } }, + "/checks/{action}": { + "put": { + "tags": ["checks"], + "summary": "Acknowledge all checks for all monitors", + "description": "Acknowledge all checks across all monitors for the team", + "parameters": [ + { + "name": "action", + "in": "path", + "required": true, + "description": "Action to perform (e.g., 'ack')", + "schema": { + "type": "string", + "enum": ["ack"] + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": ["ack"], + "properties": { + "ack": { + "type": "boolean", + "description": "Acknowledgement status to set" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Checks acknowledged successfully", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean", + "example": true + }, + "msg": { + "type": "string", + "example": "All checks acknowledged successfully" + }, + "data": { + "type": "object", + "description": "Updated checks information" + } + } + } + } + } + }, + "401": { + "$ref": "#/components/responses/Unauthorized" + }, + "500": { + "$ref": "#/components/responses/InternalServerError" + } + }, + "security": [ + { + "bearerAuth": [] + } + ] + } + }, + "/checks/{action}/{monitorId}": { + "put": { + "tags": ["checks"], + "summary": "Acknowledge all checks for a specific monitor", + "description": "Acknowledge all checks for a specific monitor", + "parameters": [ + { + "name": "action", + "in": "path", + "required": true, + "description": "Action to perform (e.g., 'ack')", + "schema": { + "type": "string", + "enum": ["ack"] + } + }, + { + "name": "monitorId", + "in": "path", + "required": true, + "description": "Monitor ID to acknowledge checks for", + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": ["ack"], + "properties": { + "ack": { + "type": "boolean", + "description": "Acknowledgement status to set" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Checks acknowledged successfully", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean", + "example": true + }, + "msg": { + "type": "string", + "example": "All checks acknowledged successfully" + }, + "data": { + "type": "object", + "description": "Updated checks information" + } + } + } + } + } + }, + "401": { + "$ref": "#/components/responses/Unauthorized" + }, + "404": { + "$ref": "#/components/responses/NotFound" + }, + "500": { + "$ref": "#/components/responses/InternalServerError" + } + }, + "security": [ + { + "bearerAuth": [] + } + ] + } + }, "/maintenance-window": { "post": { "tags": ["maintenance-window"], @@ -2291,6 +2579,142 @@ ] } }, + "/queue/jobs": { + "get": { + "tags": ["queue"], + "summary": "Get queue jobs", + "description": "Retrieve all jobs in the queue (admin/superadmin only)", + "responses": { + "200": { + "description": "Queue jobs retrieved successfully", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean", + "example": true + }, + "msg": { + "type": "string", + "example": "Queue jobs fetched successfully" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/QueueJob" + } + } + } + } + } + } + }, + "401": { + "$ref": "#/components/responses/Unauthorized" + }, + "403": { + "$ref": "#/components/responses/Forbidden" + }, + "500": { + "$ref": "#/components/responses/InternalServerError" + } + }, + "security": [ + { + "bearerAuth": [] + } + ] + }, + "post": { + "tags": ["queue"], + "summary": "Add job to queue", + "description": "Add a new job to the queue (admin/superadmin only)", + "responses": { + "200": { + "description": "Job added successfully", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean", + "example": true + }, + "msg": { + "type": "string", + "example": "Job added to queue successfully" + } + } + } + } + } + }, + "401": { + "$ref": "#/components/responses/Unauthorized" + }, + "403": { + "$ref": "#/components/responses/Forbidden" + }, + "500": { + "$ref": "#/components/responses/InternalServerError" + } + }, + "security": [ + { + "bearerAuth": [] + } + ] + } + }, + "/queue/metrics": { + "get": { + "tags": ["queue"], + "summary": "Get queue metrics", + "description": "Retrieve queue metrics (admin/superadmin only)", + "responses": { + "200": { + "description": "Queue metrics retrieved successfully", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean", + "example": true + }, + "msg": { + "type": "string", + "example": "Queue metrics fetched successfully" + }, + "data": { + "$ref": "#/components/schemas/QueueMetrics" + } + } + } + } + } + }, + "401": { + "$ref": "#/components/responses/Unauthorized" + }, + "403": { + "$ref": "#/components/responses/Forbidden" + }, + "500": { + "$ref": "#/components/responses/InternalServerError" + } + }, + "security": [ + { + "bearerAuth": [] + } + ] + } + }, "/queue/health": { "get": { "tags": ["queue"], @@ -2618,6 +3042,286 @@ } ] } + }, + "/incidents/team": { + "get": { + "tags": ["incidents"], + "summary": "Get incidents by team", + "description": "Retrieve all incidents for the authenticated user's team with optional filtering", + "parameters": [ + { + "name": "status", + "in": "query", + "description": "Filter by incident status (true = ongoing, false = resolved)", + "schema": { + "type": "boolean" + } + }, + { + "name": "monitorId", + "in": "query", + "description": "Filter by monitor ID", + "schema": { + "type": "string" + } + }, + { + "name": "page", + "in": "query", + "description": "Page number for pagination", + "schema": { + "type": "integer", + "default": 1 + } + }, + { + "name": "limit", + "in": "query", + "description": "Number of items per page", + "schema": { + "type": "integer", + "default": 10 + } + }, + { + "name": "sortOrder", + "in": "query", + "description": "Sort order for results", + "schema": { + "type": "string", + "enum": ["asc", "desc"], + "default": "desc" + } + } + ], + "responses": { + "200": { + "description": "Incidents retrieved successfully", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean", + "example": true + }, + "msg": { + "type": "string", + "example": "Incidents retrieved successfully" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Incident" + } + } + } + } + } + } + }, + "401": { + "$ref": "#/components/responses/Unauthorized" + }, + "500": { + "$ref": "#/components/responses/InternalServerError" + } + }, + "security": [ + { + "bearerAuth": [] + } + ] + } + }, + "/incidents/team/summary": { + "get": { + "tags": ["incidents"], + "summary": "Get incident summary", + "description": "Retrieve a summary of incidents for the authenticated user's team", + "parameters": [ + { + "name": "dateRange", + "in": "query", + "description": "Date range for summary", + "schema": { + "type": "string", + "enum": ["day", "week", "month"], + "default": "week" + } + } + ], + "responses": { + "200": { + "description": "Incident summary retrieved successfully", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean", + "example": true + }, + "msg": { + "type": "string", + "example": "Incident summary retrieved successfully" + }, + "data": { + "$ref": "#/components/schemas/IncidentSummary" + } + } + } + } + } + }, + "401": { + "$ref": "#/components/responses/Unauthorized" + }, + "500": { + "$ref": "#/components/responses/InternalServerError" + } + }, + "security": [ + { + "bearerAuth": [] + } + ] + } + }, + "/incidents/{incidentId}": { + "get": { + "tags": ["incidents"], + "summary": "Get incident by ID", + "description": "Retrieve a specific incident by its ID", + "parameters": [ + { + "name": "incidentId", + "in": "path", + "required": true, + "description": "The incident ID", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Incident retrieved successfully", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean", + "example": true + }, + "msg": { + "type": "string", + "example": "Incident retrieved successfully" + }, + "data": { + "$ref": "#/components/schemas/Incident" + } + } + } + } + } + }, + "401": { + "$ref": "#/components/responses/Unauthorized" + }, + "404": { + "$ref": "#/components/responses/NotFound" + }, + "500": { + "$ref": "#/components/responses/InternalServerError" + } + }, + "security": [ + { + "bearerAuth": [] + } + ] + } + }, + "/incidents/{incidentId}/resolve": { + "put": { + "tags": ["incidents"], + "summary": "Resolve incident manually", + "description": "Manually resolve an ongoing incident. Requires admin or superadmin role.", + "parameters": [ + { + "name": "incidentId", + "in": "path", + "required": true, + "description": "The incident ID to resolve", + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "comment": { + "type": "string", + "description": "Optional comment about the resolution", + "example": "Issue resolved by restarting the service" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Incident resolved successfully", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean", + "example": true + }, + "msg": { + "type": "string", + "example": "Incident resolved successfully" + }, + "data": { + "$ref": "#/components/schemas/Incident" + } + } + } + } + } + }, + "401": { + "$ref": "#/components/responses/Unauthorized" + }, + "403": { + "$ref": "#/components/responses/Forbidden" + }, + "404": { + "$ref": "#/components/responses/NotFound" + }, + "500": { + "$ref": "#/components/responses/InternalServerError" + } + }, + "security": [ + { + "bearerAuth": [] + } + ] + } } }, "components": { @@ -2680,6 +3384,16 @@ } } }, + "BadRequest": { + "description": "Invalid request parameters", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, "InternalServerError": { "description": "Internal server error", "content": { @@ -3375,6 +4089,557 @@ } } } + }, + "Incident": { + "type": "object", + "properties": { + "_id": { + "type": "string", + "description": "Unique incident identifier" + }, + "monitorId": { + "type": "string", + "description": "ID of the associated monitor" + }, + "teamId": { + "type": "string", + "description": "ID of the team" + }, + "startTime": { + "type": "string", + "format": "date-time", + "description": "When the incident started" + }, + "endTime": { + "type": ["string", "null"], + "format": "date-time", + "description": "When the incident was resolved (null if ongoing)" + }, + "status": { + "type": "boolean", + "description": "Incident status (true = ongoing, false = resolved)" + }, + "message": { + "type": ["string", "null"], + "description": "Error message or description" + }, + "statusCode": { + "type": ["integer", "null"], + "description": "HTTP status code if applicable" + }, + "resolutionType": { + "type": ["string", "null"], + "enum": ["automatic", "manual", null], + "description": "How the incident was resolved" + }, + "resolvedBy": { + "type": ["string", "null"], + "description": "User ID who resolved the incident (for manual resolution)" + }, + "comment": { + "type": ["string", "null"], + "description": "Resolution comment" + }, + "checks": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Array of check IDs associated with this incident" + }, + "createdAt": { + "type": "string", + "format": "date-time" + }, + "updatedAt": { + "type": "string", + "format": "date-time" + } + } + }, + "IncidentSummary": { + "type": "object", + "properties": { + "totalIncidents": { + "type": "integer", + "description": "Total number of incidents" + }, + "activeIncidents": { + "type": "integer", + "description": "Number of ongoing incidents" + }, + "resolvedIncidents": { + "type": "integer", + "description": "Number of resolved incidents" + }, + "averageResolutionTime": { + "type": "number", + "description": "Average time to resolve incidents in milliseconds" + }, + "incidentsByMonitor": { + "type": "array", + "items": { + "type": "object", + "properties": { + "monitorId": { + "type": "string" + }, + "monitorName": { + "type": "string" + }, + "count": { + "type": "integer" + } + } + } + } + } + }, + "QueueJob": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Job ID" + }, + "name": { + "type": "string", + "description": "Job name" + }, + "data": { + "type": "object", + "description": "Job payload data" + }, + "status": { + "type": "string", + "enum": ["waiting", "active", "completed", "failed", "delayed"], + "description": "Current job status" + }, + "progress": { + "type": "number", + "description": "Job progress percentage" + }, + "attemptsMade": { + "type": "integer", + "description": "Number of attempts made" + }, + "timestamp": { + "type": "string", + "format": "date-time", + "description": "When the job was created" + }, + "processedOn": { + "type": ["string", "null"], + "format": "date-time", + "description": "When the job started processing" + }, + "finishedOn": { + "type": ["string", "null"], + "format": "date-time", + "description": "When the job finished" + } + } + }, + "QueueMetrics": { + "type": "object", + "properties": { + "waiting": { + "type": "integer", + "description": "Number of jobs waiting" + }, + "active": { + "type": "integer", + "description": "Number of jobs currently processing" + }, + "completed": { + "type": "integer", + "description": "Number of completed jobs" + }, + "failed": { + "type": "integer", + "description": "Number of failed jobs" + }, + "delayed": { + "type": "integer", + "description": "Number of delayed jobs" + } + } + }, + "Check": { + "type": "object", + "description": "A monitoring check result", + "properties": { + "_id": { + "type": "string", + "description": "Check ID" + }, + "metadata": { + "type": "object", + "properties": { + "monitorId": { + "type": "string", + "description": "Associated monitor ID" + }, + "teamId": { + "type": "string", + "description": "Associated team ID" + }, + "type": { + "type": "string", + "enum": ["http", "ping", "pagespeed", "hardware", "docker", "port"], + "description": "Monitor type" + } + }, + "required": ["monitorId", "teamId", "type"] + }, + "status": { + "type": "boolean", + "description": "Check status (true = up, false = down)" + }, + "responseTime": { + "type": "number", + "description": "Response time in milliseconds" + }, + "statusCode": { + "type": "integer", + "description": "HTTP status code (for HTTP monitors)" + }, + "message": { + "type": "string", + "description": "Status message or error description" + }, + "timings": { + "$ref": "#/components/schemas/CheckTimings" + }, + "cpu": { + "$ref": "#/components/schemas/CheckCpuInfo" + }, + "memory": { + "$ref": "#/components/schemas/CheckMemoryInfo" + }, + "disk": { + "type": "array", + "items": { + "$ref": "#/components/schemas/CheckDiskInfo" + } + }, + "host": { + "$ref": "#/components/schemas/CheckHostInfo" + }, + "errors": { + "type": "array", + "items": { + "$ref": "#/components/schemas/CheckErrorInfo" + } + }, + "capture": { + "$ref": "#/components/schemas/CheckCaptureInfo" + }, + "net": { + "type": "array", + "items": { + "$ref": "#/components/schemas/CheckNetworkInfo" + } + }, + "accessibility": { + "type": "number", + "description": "PageSpeed accessibility score (0-100)" + }, + "bestPractices": { + "type": "number", + "description": "PageSpeed best practices score (0-100)" + }, + "seo": { + "type": "number", + "description": "PageSpeed SEO score (0-100)" + }, + "performance": { + "type": "number", + "description": "PageSpeed performance score (0-100)" + }, + "audits": { + "$ref": "#/components/schemas/CheckAudits" + }, + "ack": { + "type": "boolean", + "description": "Whether the check has been acknowledged" + }, + "ackAt": { + "type": ["string", "null"], + "format": "date-time", + "description": "When the check was acknowledged" + }, + "expiry": { + "type": "string", + "format": "date-time", + "description": "When the check expires" + }, + "createdAt": { + "type": "string", + "format": "date-time" + }, + "updatedAt": { + "type": "string", + "format": "date-time" + } + } + }, + "CheckTimings": { + "type": "object", + "description": "Detailed timing information for HTTP checks", + "properties": { + "start": { + "type": "number" + }, + "socket": { + "type": "number" + }, + "lookup": { + "type": "number" + }, + "connect": { + "type": "number" + }, + "secureConnect": { + "type": "number" + }, + "upload": { + "type": "number" + }, + "response": { + "type": "number" + }, + "end": { + "type": "number" + }, + "phases": { + "type": "object", + "properties": { + "wait": { + "type": "number" + }, + "dns": { + "type": "number" + }, + "tcp": { + "type": "number" + }, + "tls": { + "type": "number" + }, + "request": { + "type": "number" + }, + "firstByte": { + "type": "number" + }, + "download": { + "type": "number" + }, + "total": { + "type": "number" + } + } + } + } + }, + "CheckCpuInfo": { + "type": "object", + "description": "CPU information for infrastructure checks", + "properties": { + "physical_core": { + "type": "integer" + }, + "logical_core": { + "type": "integer" + }, + "frequency": { + "type": "number" + }, + "temperature": { + "type": "array", + "items": { + "type": "number" + } + }, + "free_percent": { + "type": "number" + }, + "usage_percent": { + "type": "number" + } + } + }, + "CheckMemoryInfo": { + "type": "object", + "description": "Memory information for infrastructure checks", + "properties": { + "total_bytes": { + "type": "number" + }, + "available_bytes": { + "type": "number" + }, + "used_bytes": { + "type": "number" + }, + "usage_percent": { + "type": "number" + } + } + }, + "CheckDiskInfo": { + "type": "object", + "description": "Disk information for infrastructure checks", + "properties": { + "device": { + "type": "string" + }, + "mountpoint": { + "type": "string" + }, + "read_speed_bytes": { + "type": "number" + }, + "write_speed_bytes": { + "type": "number" + }, + "total_bytes": { + "type": "number" + }, + "free_bytes": { + "type": "number" + }, + "usage_percent": { + "type": "number" + } + } + }, + "CheckHostInfo": { + "type": "object", + "description": "Host information for infrastructure checks", + "properties": { + "os": { + "type": "string" + }, + "platform": { + "type": "string" + }, + "kernel_version": { + "type": "string" + } + } + }, + "CheckErrorInfo": { + "type": "object", + "description": "Error information from checks", + "properties": { + "metric": { + "type": "array", + "items": { + "type": "string" + } + }, + "err": { + "type": "string" + } + } + }, + "CheckCaptureInfo": { + "type": "object", + "description": "Capture agent information", + "properties": { + "version": { + "type": "string" + }, + "mode": { + "type": "string" + } + } + }, + "CheckNetworkInfo": { + "type": "object", + "description": "Network interface information", + "properties": { + "name": { + "type": "string" + }, + "bytes_sent": { + "type": "number" + }, + "bytes_recv": { + "type": "number" + }, + "packets_sent": { + "type": "number" + }, + "packets_recv": { + "type": "number" + }, + "err_in": { + "type": "number" + }, + "err_out": { + "type": "number" + }, + "drop_in": { + "type": "number" + }, + "drop_out": { + "type": "number" + }, + "fifo_in": { + "type": "number" + }, + "fifo_out": { + "type": "number" + } + } + }, + "CheckAudits": { + "type": "object", + "description": "PageSpeed audit results", + "properties": { + "cls": { + "$ref": "#/components/schemas/LighthouseAudit" + }, + "si": { + "$ref": "#/components/schemas/LighthouseAudit" + }, + "fcp": { + "$ref": "#/components/schemas/LighthouseAudit" + }, + "lcp": { + "$ref": "#/components/schemas/LighthouseAudit" + }, + "tbt": { + "$ref": "#/components/schemas/LighthouseAudit" + } + } + }, + "LighthouseAudit": { + "type": "object", + "description": "Individual Lighthouse audit result", + "properties": { + "id": { + "type": "string" + }, + "title": { + "type": "string" + }, + "score": { + "type": "number" + }, + "displayValue": { + "type": "string" + }, + "numericValue": { + "type": "number" + }, + "numericUnit": { + "type": "string" + } + } } } } diff --git a/server/src/config/controllers.ts b/server/src/config/controllers.ts index 9fe834348..5ddbf2a06 100644 --- a/server/src/config/controllers.ts +++ b/server/src/config/controllers.ts @@ -10,8 +10,8 @@ import StatusPageController from "../controllers/statusPageController.js"; import NotificationController from "../controllers/notificationController.js"; import DiagnosticController from "../controllers/diagnosticController.js"; import IncidentController from "../controllers/incidentController.js"; - -export const initializeControllers = (services: any) => { +import type { InitializedSerivces } from "@/config/services.js"; +export const initializeControllers = (services: InitializedSerivces) => { const controllers: Record = {}; controllers.authController = new AuthController(services.userService); @@ -26,7 +26,7 @@ export const initializeControllers = (services: any) => { controllers.queueController = new QueueController(services.jobQueue); controllers.logController = new LogController(services.logger); controllers.statusPageController = new StatusPageController(services.db); - controllers.notificationController = new NotificationController(services.notificationService, services.db); + controllers.notificationController = new NotificationController(services.notificationsService, services.db, services.monitorsRepository); controllers.diagnosticController = new DiagnosticController(services.diagnosticService); controllers.incidentController = new IncidentController(services.incidentService); diff --git a/server/src/config/services.ts b/server/src/config/services.ts index 74c68c86e..e3587c662 100644 --- a/server/src/config/services.ts +++ b/server/src/config/services.ts @@ -5,9 +5,17 @@ import MongoDB from "../db/MongoDB.js"; import NetworkService from "../service/infrastructure/networkService.js"; import EmailService from "../service/infrastructure/emailService.js"; import BufferService from "../service/infrastructure/bufferService.js"; -import StatusService from "../service/infrastructure/statusService.js"; -import NotificationUtils from "../service/infrastructure/notificationUtils.js"; -import NotificationService from "../service/infrastructure/notificationService.js"; +import { + NotificationsService, + StatusService, + WebhookProvider, + SlackProvider, + EmailProvider, + DiscordProvider, + PagerDutyProvider, + MatrixProvider, + INotificationsService, +} from "@/service/index.js"; import ErrorService from "../service/infrastructure/errorService.js"; import SuperSimpleQueueHelper from "../service/infrastructure/SuperSimpleQueue/SuperSimpleQueueHelper.js"; import SuperSimpleQueue from "../service/infrastructure/SuperSimpleQueue/SuperSimpleQueue.js"; @@ -37,9 +45,6 @@ import crypto from "crypto"; import { games, GameDig } from "gamedig"; import jmespath from "jmespath"; -import { fileURLToPath } from "url"; -import { ObjectId } from "mongodb"; - // DB Modules import { NormalizeData, NormalizeDataUptimeDetails } from "../utils/dataUtils.js"; import { GenerateAvatarImage } from "../utils/imageProcessing.js"; @@ -48,31 +53,93 @@ import { ParseBoolean } from "../utils/utils.js"; // Models import Monitor from "../db/models/Monitor.js"; import User from "../db/models/User.js"; -import InviteToken from "../db/models/InviteToken.js"; +import InviteToken from "../db/models/Invite.js"; import StatusPage from "../db/models/StatusPage.js"; import Team from "../db/models/Team.js"; import MaintenanceWindow from "../db/models/MaintenanceWindow.js"; import MonitorStats from "../db/models/MonitorStats.js"; -import Notification from "../db/models/Notification.js"; +import NotificationModel from "../db/models/Notification.js"; import RecoveryToken from "../db/models/RecoveryToken.js"; import AppSettings from "../db/models/AppSettings.js"; import Incident from "../db/models/Incident.js"; import InviteModule from "../db/modules/inviteModule.js"; -import CheckModule from "../db/modules/checkModule.js"; import StatusPageModule from "../db/modules/statusPageModule.js"; import UserModule from "../db/modules/userModule.js"; import MaintenanceWindowModule from "../db/modules/maintenanceWindowModule.js"; -import MonitorModule from "../db/modules/monitorModule.js"; import NotificationModule from "../db/modules/notificationModule.js"; import RecoveryModule from "../db/modules/recoveryModule.js"; import SettingsModule from "../db/modules/settingsModule.js"; import IncidentModule from "../db/modules/incidentModule.js"; // repositories -import { MongoMonitorsRepository, MongoChecksRepository, MongoMonitorStatsRepository } from "@/repositories/index.js"; +import { + MongoMonitorsRepository, + MongoChecksRepository, + MongoMonitorStatsRepository, + MongoStatusPagesRepository, + MongoUsersRepository, + MongoInvitesRepository, + MongoRecoveryTokensRepository, + MongoSettingsRepository, + MongoNotificationsRepository, + MongoIncidentRepository, + IMonitorsRepository, + IChecksRepository, + IMonitorStatsRepository, + IStatusPagesRepository, + IUsersRepository, + IInvitesRepository, + IRecoveryTokensRepository, + ISettingsRepository, + INotificationsRepository, + IIncidentsRepository, +} from "@/repositories/index.js"; -export const initializeServices = async ({ logger, envSettings, settingsService }: { logger: any; envSettings: any; settingsService: any }) => { +export type InitializedSerivces = { + //v1 + settingsService: any; + translationService: any; + stringService: any; + db: any; + networkService: any; + emailService: any; + bufferService: any; + statusService: any; + jobQueue: any; + userService: any; + checkService: any; + diagnosticService: any; + inviteService: any; + maintenanceWindowService: any; + monitorService: any; + incidentService: any; + errorService: any; + logger: any; + notificationsService: INotificationsService; + + // Repositories + monitorsRepository: IMonitorsRepository; + checksRepository: IChecksRepository; + monitorStatsRepository: IMonitorStatsRepository; + statusPagesRepository: IStatusPagesRepository; + usersRepository: IUsersRepository; + invitesRepository: IInvitesRepository; + recoveryTokensRepository: IRecoveryTokensRepository; + settingsRepository: ISettingsRepository; + notificationsRepository: INotificationsRepository; + incidentsRepository: IIncidentsRepository; +}; + +export const initializeServices = async ({ + logger, + envSettings, + settingsService, +}: { + logger: any; + envSettings: any; + settingsService: any; +}): Promise => { const serviceRegistry = new ServiceRegistry({ logger }); (ServiceRegistry as any).instance = serviceRegistry; @@ -82,23 +149,11 @@ export const initializeServices = async ({ logger, envSettings, settingsService const stringService = new StringService(translationService); // Create DB - const checkModule = new CheckModule({ logger, Monitor, User }); const inviteModule = new InviteModule({ InviteToken, crypto, stringService }); - const statusPageModule = new StatusPageModule({ StatusPage, NormalizeData, stringService }); + const statusPageModule = new StatusPageModule({ StatusPage, NormalizeData, stringService, AppSettings }); const userModule = new UserModule({ User, Team, GenerateAvatarImage, ParseBoolean, stringService }); const maintenanceWindowModule = new MaintenanceWindowModule({ MaintenanceWindow }); - const monitorModule = new MonitorModule({ - Monitor, - MonitorStats, - stringService, - fs, - path, - fileURLToPath, - ObjectId, - NormalizeData, - NormalizeDataUptimeDetails, - }); - const notificationModule = new NotificationModule({ Notification, Monitor }); + const notificationModule = new NotificationModule({ Notification: NotificationModel, Monitor }); const recoveryModule = new RecoveryModule({ User, RecoveryToken, crypto, stringService }); const settingsModule = new SettingsModule({ AppSettings }); const incidentModule = new IncidentModule({ logger, Incident, Monitor, User }); @@ -106,12 +161,10 @@ export const initializeServices = async ({ logger, envSettings, settingsService const db = new MongoDB({ logger, envSettings, - checkModule, inviteModule, statusPageModule, userModule, maintenanceWindowModule, - monitorModule, notificationModule, recoveryModule, settingsModule, @@ -122,9 +175,15 @@ export const initializeServices = async ({ logger, envSettings, settingsService // Repositories const monitorsRepository = new MongoMonitorsRepository(); - const checksRepository = new MongoChecksRepository(); + const checksRepository = new MongoChecksRepository(logger); const monitorStatsRepository = new MongoMonitorStatsRepository(); - + const statusPagesRepository = new MongoStatusPagesRepository(); + const usersRepository = new MongoUsersRepository(); + const invitesRepository = new MongoInvitesRepository(); + const recoveryTokensRepository = new MongoRecoveryTokensRepository(); + const settingsRepository = new MongoSettingsRepository(); + const notificationsRepository = new MongoNotificationsRepository(); + const incidentsRepository = new MongoIncidentRepository(); const networkService = new NetworkService({ axios, got, @@ -147,38 +206,50 @@ export const initializeServices = async ({ logger, envSettings, settingsService logger, errorService, stringService, + incidentsRepository, }); - const bufferService = new BufferService({ db, logger, envSettings, incidentService }); - - const statusService = new StatusService({ db, logger, buffer: bufferService, incidentService, monitorsRepository }); - - const notificationUtils = new NotificationUtils({ - stringService, - emailService, - settingsService, - }); - - const notificationService = new NotificationService({ - emailService, - db, + const checkService = new CheckService({ + errorService, + monitorsRepository, logger, - networkService, - stringService, - notificationUtils, + checksRepository, }); + const bufferService = new BufferService({ logger, checkService }); + + const statusService = new StatusService({ db, logger, buffer: bufferService, monitorsRepository }); + + const webhookProvider = new WebhookProvider(logger); + const slackProvider = new SlackProvider(logger); + const emailProvider = new EmailProvider(emailService, logger); + const discordProvider = new DiscordProvider(logger); + const pagerDutyProvider = new PagerDutyProvider(logger); + const matrixProvider = new MatrixProvider(logger); + + const notificationsService = new NotificationsService( + notificationsRepository, + webhookProvider, + emailProvider, + slackProvider, + discordProvider, + pagerDutyProvider, + matrixProvider, + logger + ); + const superSimpleQueueHelper = new SuperSimpleQueueHelper({ db, logger, networkService, statusService, - notificationService, + notificationsService, + checkService, + buffer: bufferService, + incidentService, }); const superSimpleQueue = await SuperSimpleQueue.create({ - envSettings, - db, logger, helper: superSimpleQueueHelper, monitorsRepository, @@ -187,7 +258,6 @@ export const initializeServices = async ({ logger, envSettings, settingsService // Business services const userService = new UserService({ crypto, - db, emailService, settingsService, logger, @@ -195,19 +265,18 @@ export const initializeServices = async ({ logger, envSettings, settingsService jwt, errorService, jobQueue: superSimpleQueue, + monitorsRepository, + usersRepository, + invitesRepository, + recoveryTokensRepository, + settingsRepository, }); - const checkService = new CheckService({ - db, - settingsService, - stringService, - errorService, - }); + const diagnosticService = new DiagnosticService(); const inviteService = new InviteService({ - db, + invitesRepository, settingsService, emailService, - stringService, errorService, }); const maintenanceWindowService = new MaintenanceWindowService({ @@ -215,9 +284,9 @@ export const initializeServices = async ({ logger, envSettings, settingsService settingsService, stringService, errorService, + monitorsRepository, }); const monitorService = new MonitorService({ - db, jobQueue: superSimpleQueue, stringService, emailService, @@ -228,6 +297,7 @@ export const initializeServices = async ({ logger, envSettings, settingsService monitorsRepository, checksRepository, monitorStatsRepository, + statusPagesRepository, }); const services = { @@ -240,7 +310,6 @@ export const initializeServices = async ({ logger, envSettings, settingsService emailService, bufferService, statusService, - notificationService, jobQueue: superSimpleQueue, userService, checkService, @@ -251,6 +320,19 @@ export const initializeServices = async ({ logger, envSettings, settingsService incidentService, errorService, logger, + notificationsService, + + // Repositories + monitorsRepository, + checksRepository, + monitorStatsRepository, + statusPagesRepository, + usersRepository, + invitesRepository, + recoveryTokensRepository, + settingsRepository, + notificationsRepository, + incidentsRepository, }; Object.values(services).forEach((service) => { diff --git a/server/src/controllers/authController.ts b/server/src/controllers/authController.ts index d033aa39d..23ea6e42e 100755 --- a/server/src/controllers/authController.ts +++ b/server/src/controllers/authController.ts @@ -32,11 +32,14 @@ class AuthController { registerUser = async (req: Request, res: Response, next: NextFunction) => { try { - if (req.body?.email) { - req.body.email = req.body.email?.toLowerCase(); + const newUser = req.body.user; + const newUserToken = req.body.token; + if (newUser?.email) { + newUser.email = newUser.email.toLowerCase(); } - await registrationBodyValidation.validateAsync(req.body); - const { user, token } = await this.userService.registerUser(req.body, req.file); + await registrationBodyValidation.validateAsync(newUser); + + const { user, token } = await this.userService.registerUser(newUser, newUserToken, req.file); res.status(200).json({ success: true, msg: "User registered successfully", @@ -189,7 +192,8 @@ class AuthController { editUserById = async (req: Request, res: Response, next: NextFunction) => { try { const roles = req?.user?.role; - if (!roles.includes("superadmin")) { + + if (!roles || !roles.includes("superadmin")) { throw new AppError({ message: "Unauthorized", status: 403 }); } @@ -198,7 +202,7 @@ class AuthController { await editUserByIdParamValidation.validateAsync(req.params); // If this is superadmin self edit, allow "superadmin" role - if (userId === req.user._id) { + if (userId === req.user?.id) { await editSuperadminUserByIdBodyValidation.validateAsync(req.body); } else { await editUserByIdBodyValidation.validateAsync(req.body); @@ -214,7 +218,7 @@ class AuthController { editUserPasswordById = async (req: Request, res: Response, next: NextFunction) => { try { const roles = req?.user?.role; - if (!roles.includes("superadmin")) { + if (!roles || !roles.includes("superadmin")) { throw new AppError({ message: "Unauthorized", status: 403 }); } diff --git a/server/src/controllers/checkController.ts b/server/src/controllers/checkController.ts index 8ae6fd785..8277df3e7 100755 --- a/server/src/controllers/checkController.ts +++ b/server/src/controllers/checkController.ts @@ -77,53 +77,6 @@ class CheckController { } }; - ackCheck = async (req: Request, res: Response, next: NextFunction) => { - try { - await ackCheckBodyValidation.validateAsync(req.body); - - const updatedCheck = await this.checkService.ackCheck({ - checkId: req?.params?.checkId, - teamId: req?.user?.teamId, - ack: req?.body?.ack, - }); - - return res.status(200).json({ - success: true, - msg: "Check acknowledged successfully", - data: updatedCheck, - }); - } catch (error) { - next(error); - } - }; - - ackAllChecks = async (req: Request, res: Response, next: NextFunction) => { - try { - await ackAllChecksParamValidation.validateAsync(req.params); - await ackAllChecksBodyValidation.validateAsync(req.body); - - const teamId = req?.user?.teamId; - if (!teamId) { - throw new Error("No team ID in request"); - } - - const updatedChecks = await this.checkService.ackAllChecks({ - monitorId: req?.params?.monitorId, - path: req?.params?.path, - teamId: req?.user?.teamId, - ack: req?.body?.ack, - }); - - return res.status(200).json({ - success: true, - msg: "All checks acknowledged successfully", - data: updatedChecks, - }); - } catch (error) { - next(error); - } - }; - deleteChecks = async (req: Request, res: Response, next: NextFunction) => { try { await deleteChecksParamValidation.validateAsync(req.params); diff --git a/server/src/controllers/incidentController.ts b/server/src/controllers/incidentController.ts index 8a56b5ef8..93783b20c 100644 --- a/server/src/controllers/incidentController.ts +++ b/server/src/controllers/incidentController.ts @@ -1,3 +1,4 @@ +import { AppError } from "@/utils/AppError.js"; import { Request, Response, NextFunction } from "express"; const SERVICE_NAME = "incidentController"; @@ -33,10 +34,15 @@ class IncidentController { getIncidentSummary = async (req: Request, res: Response, next: NextFunction) => { try { - const summary = await this.incidentService.getIncidentSummary({ - teamId: req?.user?.teamId, - query: req?.query, - }); + const teamId = req.user?.teamId; + + if (!teamId) { + throw new AppError({ message: "Team ID is required", service: SERVICE_NAME, status: 400 }); + } + + const limit = req.query.limit ? parseInt(req.query.limit as string, 10) : 10; + + const summary = await this.incidentService.getIncidentSummary(req?.user?.teamId, limit); return res.status(200).json({ success: true, @@ -67,12 +73,12 @@ class IncidentController { resolveIncidentManually = async (req: Request, res: Response, next: NextFunction) => { try { - const resolvedIncident = await this.incidentService.resolveIncidentManually({ - incidentId: req?.params?.incidentId, - userId: req?.user?._id, - teamId: req?.user?.teamId, - comment: req?.body?.comment, - }); + const resolvedIncident = await this.incidentService.resolveIncident( + req?.params?.incidentId, + req?.user?.id, + req?.user?.teamId, + req?.body?.comment + ); return res.status(200).json({ success: true, diff --git a/server/src/controllers/maintenanceWindowController.ts b/server/src/controllers/maintenanceWindowController.ts index afeba9219..3d212769f 100644 --- a/server/src/controllers/maintenanceWindowController.ts +++ b/server/src/controllers/maintenanceWindowController.ts @@ -46,7 +46,7 @@ class MaintenanceWindowController { try { await getMaintenanceWindowByIdParamValidation.validateAsync(req.params); - const teamId = req.user.teamId; + const teamId = req.user?.teamId; if (!teamId) { throw new AppError({ message: "Team ID is required", status: 400 }); } @@ -130,7 +130,7 @@ class MaintenanceWindowController { await editMaintenanceWindowByIdParamValidation.validateAsync(req.params); await editMaintenanceByIdWindowBodyValidation.validateAsync(req.body); - const teamId = req.user.teamId; + const teamId = req.user?.teamId; if (!teamId) { throw new AppError({ message: "Team ID is required", status: 400 }); } diff --git a/server/src/controllers/monitorController.ts b/server/src/controllers/monitorController.ts index 90ab5e7a5..fcb731283 100644 --- a/server/src/controllers/monitorController.ts +++ b/server/src/controllers/monitorController.ts @@ -97,7 +97,7 @@ class MonitorController { await getHardwareDetailsByIdQueryValidation.validateAsync(req.query); const monitorId = requireString(req?.params?.monitorId, "Monitor ID"); - const dateRange = requireString(req?.query?.dateRange, "dateRange"); + const dateRange = optionalString(req?.query?.dateRange, "dateRange") || "recent"; const teamId = requireTeamId(req?.user?.teamId); const monitor = await this.monitorService.getHardwareDetailsById({ @@ -124,7 +124,7 @@ class MonitorController { const dateRange = requireString(req?.query?.dateRange, "dateRange"); const teamId = requireTeamId(req?.user?.teamId); - const monitor = await this.monitorService.getPageSpeedDetailsById({ + const data = await this.monitorService.getPageSpeedDetailsById({ teamId, monitorId, dateRange, @@ -133,7 +133,7 @@ class MonitorController { return res.status(200).json({ success: true, msg: "Page speed details retrieved successfully", - data: monitor, + data, }); } catch (error) { next(error); @@ -164,7 +164,7 @@ class MonitorController { try { await createMonitorBodyValidation.validateAsync(req.body); - const userId = requireString(req?.user?._id, "User ID"); + const userId = requireString(req?.user?.id, "User ID"); const teamId = requireTeamId(req?.user?.teamId); const monitor = await this.monitorService.createMonitor(teamId, userId, req.body); @@ -193,7 +193,7 @@ class MonitorController { throw new AppError({ message: "File is empty", status: 400 }); } - const userId = requireString(req?.user?._id, "User ID"); + const userId = requireString(req?.user?.id, "User ID"); const teamId = requireTeamId(req?.user?.teamId); const fileData = req?.file?.buffer?.toString("utf-8"); @@ -286,9 +286,9 @@ class MonitorController { addDemoMonitors = async (req: Request, res: Response, next: NextFunction) => { try { - const _id = requireString(req?.user?._id, "User ID"); + const id = requireString(req?.user?.id, "User ID"); const teamId = requireTeamId(req?.user?.teamId); - const demoMonitors = await this.monitorService.addDemoMonitors({ userId: _id, teamId }); + const demoMonitors = await this.monitorService.addDemoMonitors({ userId: id, teamId }); return res.status(200).json({ success: true, @@ -339,26 +339,6 @@ class MonitorController { } }; - getMonitorsAndSummaryByTeamId = async (req: Request, res: Response, next: NextFunction) => { - try { - await getMonitorsByTeamIdParamValidation.validateAsync(req.params); - await getMonitorsByTeamIdQueryValidation.validateAsync(req.query); - - const explain = optionalBoolean(req?.query?.explain, "explain"); - const type = parseMonitorTypeFilter(req?.query?.type); - const teamId = requireTeamId(req?.user?.teamId); - - const result = await this.monitorService.getMonitorsAndSummaryByTeamId({ teamId, type, explain }); - - return res.status(200).json({ - msg: "Monitors and summary retrieved successfully", - data: result, - }); - } catch (error) { - next(error); - } - }; - getMonitorsWithChecksByTeamId = async (req: Request, res: Response, next: NextFunction) => { try { await getMonitorsByTeamIdParamValidation.validateAsync(req.params); @@ -394,21 +374,6 @@ class MonitorController { next(error); } }; - exportMonitorsToCSV = async (req: Request, res: Response, next: NextFunction) => { - try { - const teamId = req?.user?.teamId; - if (!teamId) { - throw new AppError({ message: "Team ID is required", status: 400 }); - } - - const csv = await this.monitorService.exportMonitorsToCSV({ teamId }); - res.setHeader("Content-Type", "text/csv"); - res.setHeader("Content-Disposition", "attachment; filename=monitors.csv"); - return res.send(csv); - } catch (error) { - next(error); - } - }; exportMonitorsToJSON = async (req: Request, res: Response, next: NextFunction) => { try { diff --git a/server/src/controllers/notificationController.ts b/server/src/controllers/notificationController.ts index 74849c6aa..1569f0986 100644 --- a/server/src/controllers/notificationController.ts +++ b/server/src/controllers/notificationController.ts @@ -1,17 +1,22 @@ import { Request, Response, NextFunction } from "express"; +import { Notification } from "@/types/index.js"; import { createNotificationBodyValidation } from "@/validation/joi.js"; import { AppError } from "@/utils/AppError.js"; +import { IMonitorsRepository } from "@/repositories/index.js"; +import { INotificationsService } from "@/service/index.js"; const SERVICE_NAME = "NotificationController"; class NotificationController { static SERVICE_NAME = SERVICE_NAME; private db: any; - private notificationService: any; - constructor(notificationService: any, db: any) { - this.notificationService = notificationService; + private notificationsService: INotificationsService; + private monitorsRepository: IMonitorsRepository; + constructor(notificationsService: INotificationsService, db: any, monitorsRepository: IMonitorsRepository) { + this.notificationsService = notificationsService; this.db = db; + this.monitorsRepository = monitorsRepository; } get serviceName() { @@ -20,9 +25,8 @@ class NotificationController { testNotification = async (req: Request, res: Response, next: NextFunction) => { try { - const notification = req.body; - - const success = await this.notificationService.sendTestNotification(notification); + const notification: Notification = req.body; + const success = await this.notificationsService.sendTestNotification(notification); if (!success) { throw new AppError({ message: "Sending notification failed", status: 500 }); @@ -50,7 +54,7 @@ class NotificationController { throw new AppError({ message: "Team ID is required", status: 400 }); } - const userId = req?.user?._id; + const userId = req?.user?.id; if (!userId) { throw new AppError({ message: "User ID is required", status: 400 }); } @@ -167,18 +171,14 @@ class NotificationController { throw new AppError({ message: "Team ID is required", status: 400 }); } - const monitor = await this.db.monitorModule.getMonitorById(monitorId); - - if (!monitor.teamId.equals(teamId)) { - throw new AppError({ message: "Unauthorized", status: 403 }); - } + const monitor = await this.monitorsRepository.findById(monitorId, teamId); const notifications = monitor.notifications; if (notifications.length === 0) { throw new AppError({ message: "No notifications", status: 400 }); } - const result = await this.notificationService.testAllNotifications(notifications); + const result = await this.notificationsService.testAllNotifications(notifications); if (!result) { throw new AppError({ message: "Failed to send all notifications", status: 500 }); diff --git a/server/src/controllers/statusPageController.ts b/server/src/controllers/statusPageController.ts index 105beb230..b63e925c0 100644 --- a/server/src/controllers/statusPageController.ts +++ b/server/src/controllers/statusPageController.ts @@ -21,11 +21,11 @@ class StatusPageController { await createStatusPageBodyValidation.validateAsync(req.body); await imageValidation.validateAsync(req.file); - const { _id, teamId } = req.user; + const { id, teamId } = req.user ?? {}; const statusPage = await this.db.statusPageModule.createStatusPage({ statusPageData: req.body, image: req.file, - userId: _id, + userId: id, teamId, }); return res.status(200).json({ @@ -87,7 +87,7 @@ class StatusPageController { }; getStatusPagesByTeamId = async (req: Request, res: Response, next: NextFunction) => { try { - const teamId = req.user.teamId; + const teamId = req.user?.teamId; const statusPages = await this.db.statusPageModule.getStatusPagesByTeamId(teamId); return res.status(200).json({ diff --git a/server/src/db/MongoDB.js b/server/src/db/MongoDB.js index 3db17c78f..a0c580f1d 100755 --- a/server/src/db/MongoDB.js +++ b/server/src/db/MongoDB.js @@ -7,12 +7,10 @@ class MongoDB { constructor({ logger, envSettings, - checkModule, inviteModule, statusPageModule, userModule, maintenanceWindowModule, - monitorModule, notificationModule, recoveryModule, settingsModule, @@ -23,9 +21,7 @@ class MongoDB { this.userModule = userModule; this.inviteModule = inviteModule; this.recoveryModule = recoveryModule; - this.checkModule = checkModule; this.maintenanceWindowModule = maintenanceWindowModule; - this.monitorModule = monitorModule; this.notificationModule = notificationModule; this.settingsModule = settingsModule; this.statusPageModule = statusPageModule; diff --git a/server/src/db/models/AppSettings.js b/server/src/db/models/AppSettings.js deleted file mode 100755 index 2313d638c..000000000 --- a/server/src/db/models/AppSettings.js +++ /dev/null @@ -1,80 +0,0 @@ -import mongoose from "mongoose"; - -const AppSettingsSchema = mongoose.Schema( - { - checkTTL: { - type: Number, - default: 30, - }, - language: { - type: String, - default: "gb", - }, - pagespeedApiKey: { - type: String, - }, - systemEmailHost: { - type: String, - }, - systemEmailPort: { - type: Number, - }, - systemEmailAddress: { - type: String, - }, - systemEmailPassword: { - type: String, - }, - systemEmailUser: { - type: String, - }, - systemEmailConnectionHost: { - type: String, - default: "localhost", - }, - systemEmailTLSServername: { - type: String, - }, - systemEmailSecure: { - type: Boolean, - default: false, - }, - systemEmailPool: { - type: Boolean, - default: false, - }, - systemEmailIgnoreTLS: { - type: Boolean, - default: false, - }, - systemEmailRequireTLS: { - type: Boolean, - default: false, - }, - systemEmailRejectUnauthorized: { - type: Boolean, - default: true, - }, - singleton: { - type: Boolean, - required: true, - unique: true, - default: true, - }, - version: { - type: Number, - default: 1, - }, - globalThresholds: { - cpu: { type: Number }, - memory: { type: Number }, - disk: { type: Number }, - temperature: { type: Number }, - }, - }, - { - timestamps: true, - } -); - -export default mongoose.model("AppSettings", AppSettingsSchema); diff --git a/server/src/db/models/AppSettings.ts b/server/src/db/models/AppSettings.ts new file mode 100644 index 000000000..9eeaa640a --- /dev/null +++ b/server/src/db/models/AppSettings.ts @@ -0,0 +1,50 @@ +import { Schema, model, type Types } from "mongoose"; +import type { Settings, SettingsThresholds } from "@/types/settings.js"; + +interface AppSettingsDocument extends Omit { + _id: Types.ObjectId; + createdAt: Date; + updatedAt: Date; +} + +const thresholdsSchema = new Schema( + { + cpu: { type: Number }, + memory: { type: Number }, + disk: { type: Number }, + temperature: { type: Number }, + }, + { _id: false } +); + +const AppSettingsSchema = new Schema( + { + checkTTL: { type: Number, default: 30 }, + language: { type: String, default: "gb" }, + jwtSecret: { type: String }, + pagespeedApiKey: { type: String }, + systemEmailHost: { type: String }, + systemEmailPort: { type: Number }, + systemEmailAddress: { type: String }, + systemEmailPassword: { type: String }, + systemEmailUser: { type: String }, + systemEmailConnectionHost: { type: String, default: "localhost" }, + systemEmailTLSServername: { type: String }, + systemEmailSecure: { type: Boolean, default: false }, + systemEmailPool: { type: Boolean, default: false }, + systemEmailIgnoreTLS: { type: Boolean, default: false }, + systemEmailRequireTLS: { type: Boolean, default: false }, + systemEmailRejectUnauthorized: { type: Boolean, default: true }, + showURL: { type: Boolean, default: false }, + singleton: { type: Boolean, required: true, unique: true, default: true }, + version: { type: Number, default: 1 }, + globalThresholds: { type: thresholdsSchema }, + }, + { timestamps: true } +); + +const AppSettingsModel = model("AppSettings", AppSettingsSchema); + +export type { AppSettingsDocument }; +export { AppSettingsModel }; +export default AppSettingsModel; diff --git a/server/src/db/models/Check.ts b/server/src/db/models/Check.ts index c176aa3bb..94dfa873c 100644 --- a/server/src/db/models/Check.ts +++ b/server/src/db/models/Check.ts @@ -11,8 +11,7 @@ import type { CheckMemoryInfo, CheckMetadata, CheckNetworkInterfaceInfo, - CheckTimings, - CheckTimingPhases, + GotTimings, ILighthouseAudit, } from "@/types/check.js"; @@ -35,7 +34,7 @@ interface CheckDocument extends CheckDocumentBase { _id: Types.ObjectId; } -const timingPhasesSchema = new Schema( +const timingPhasesSchema = new Schema( { wait: { type: Number, default: 0 }, dns: { type: Number, default: 0 }, @@ -49,7 +48,7 @@ const timingPhasesSchema = new Schema( { _id: false } ); -const timingsSchema = new Schema( +const timingsSchema = new Schema( { start: { type: Number, default: 0 }, socket: { type: Number, default: 0 }, diff --git a/server/src/db/models/Incident.js b/server/src/db/models/Incident.ts similarity index 55% rename from server/src/db/models/Incident.js rename to server/src/db/models/Incident.ts index a9477301b..8de1c7c2c 100644 --- a/server/src/db/models/Incident.js +++ b/server/src/db/models/Incident.ts @@ -1,16 +1,31 @@ -import mongoose from "mongoose"; +import { Schema, model, type Types } from "mongoose"; +import { IncidentResolutionTypes, type Incident } from "@/types/incident.js"; -const IncidentSchema = mongoose.Schema( +type IncidentDocumentBase = Omit & { + monitorId: Types.ObjectId; + teamId: Types.ObjectId; + resolvedBy?: Types.ObjectId | null; + startTime: Date; + endTime: Date | null; + createdAt: Date; + updatedAt: Date; +}; + +export interface IncidentDocument extends IncidentDocumentBase { + _id: Types.ObjectId; +} + +const IncidentSchema = new Schema( { monitorId: { - type: mongoose.Schema.Types.ObjectId, + type: Schema.Types.ObjectId, ref: "Monitor", required: true, immutable: true, index: true, }, teamId: { - type: mongoose.Schema.Types.ObjectId, + type: Schema.Types.ObjectId, ref: "Team", required: true, immutable: true, @@ -18,8 +33,8 @@ const IncidentSchema = mongoose.Schema( }, startTime: { type: Date, - required: true, immutable: true, + required: true, }, endTime: { type: Date, @@ -36,16 +51,16 @@ const IncidentSchema = mongoose.Schema( }, statusCode: { type: Number, - index: true, default: null, + index: true, }, resolutionType: { type: String, - enum: ["automatic", "manual"], + enum: IncidentResolutionTypes, default: null, }, resolvedBy: { - type: mongoose.Schema.Types.ObjectId, + type: Schema.Types.ObjectId, ref: "User", default: null, }, @@ -53,12 +68,6 @@ const IncidentSchema = mongoose.Schema( type: String, default: null, }, - checks: [ - { - type: mongoose.Schema.Types.ObjectId, - ref: "Check", - }, - ], }, { timestamps: true } ); @@ -71,6 +80,7 @@ IncidentSchema.index({ resolutionType: 1, status: 1 }); IncidentSchema.index({ resolvedBy: 1, status: 1 }); IncidentSchema.index({ createdAt: -1 }); -const Incident = mongoose.model("Incident", IncidentSchema); +const IncidentModel = model("Incident", IncidentSchema); -export default Incident; +export { IncidentModel }; +export default IncidentModel; diff --git a/server/src/db/models/Invite.ts b/server/src/db/models/Invite.ts new file mode 100755 index 000000000..25ddd9a72 --- /dev/null +++ b/server/src/db/models/Invite.ts @@ -0,0 +1,30 @@ +import { Schema, model, type Types } from "mongoose"; +import type { Invite } from "@/types/invite.js"; + +type InviteDocumentBase = Omit & { + teamId: Types.ObjectId; + expiry: Date; +}; + +interface InviteDocument extends InviteDocumentBase { + _id: Types.ObjectId; + createdAt: Date; + updatedAt: Date; +} + +const InviteSchema = new Schema( + { + email: { type: String, required: true, unique: true }, + teamId: { type: Schema.Types.ObjectId, ref: "Team", immutable: true, required: true }, + role: { type: [String], required: true, default: ["user"] }, + token: { type: String, required: true }, + expiry: { type: Date, default: Date.now, expires: 3600 }, + }, + { timestamps: true } +); + +const InviteModel = model("Invite", InviteSchema); + +export type { InviteDocument }; +export { InviteModel }; +export default InviteModel; diff --git a/server/src/db/models/InviteToken.js b/server/src/db/models/InviteToken.js deleted file mode 100755 index 079600647..000000000 --- a/server/src/db/models/InviteToken.js +++ /dev/null @@ -1,35 +0,0 @@ -import mongoose from "mongoose"; -const InviteTokenSchema = mongoose.Schema( - { - email: { - type: String, - required: true, - unique: true, - }, - teamId: { - type: mongoose.Schema.Types.ObjectId, - ref: "Team", - immutable: true, - required: true, - }, - role: { - type: Array, - required: true, - default: ["user"], - }, - token: { - type: String, - required: true, - }, - expiry: { - type: Date, - default: Date.now, - expires: 3600, - }, - }, - { - timestamps: true, - } -); - -export default mongoose.model("InviteToken", InviteTokenSchema); diff --git a/server/src/db/models/Monitor.ts b/server/src/db/models/Monitor.ts index f6f9d4371..17565a2e4 100644 --- a/server/src/db/models/Monitor.ts +++ b/server/src/db/models/Monitor.ts @@ -171,35 +171,6 @@ const MonitorSchema = new Schema( } ); -MonitorSchema.pre("findOneAndDelete", async function (next) { - try { - const doc = await this.model.findOne(this.getFilter()); - - if (!doc) { - throw new Error("Monitor not found"); - } - - await Check.deleteMany({ monitorId: doc._id }); - await StatusPage.updateMany({ monitors: doc?._id }, { $pull: { monitors: doc?._id } }); - await MonitorStats.deleteMany({ monitorId: doc?._id.toString() }); - next(); - } catch (error) { - next(error as Error); - } -}); - -MonitorSchema.pre("deleteMany", async function (next) { - const filter = this.getFilter(); - const monitors = (await this.model.find(filter).select(["_id", "type"]).lean()) as { _id: Types.ObjectId }[]; - - for (const monitor of monitors) { - await Check.deleteMany({ monitorId: monitor._id }); - await StatusPage.updateMany({ monitors: monitor._id }, { $pull: { monitors: monitor._id } }); - await MonitorStats.deleteMany({ monitorId: monitor._id.toString() }); - } - next(); -}); - MonitorSchema.pre("save", function (next) { if (!this.cpuAlertThreshold || this.isModified("alertThreshold")) { this.cpuAlertThreshold = this.alertThreshold; diff --git a/server/src/db/models/Notification.js b/server/src/db/models/Notification.js deleted file mode 100755 index 72c716a26..000000000 --- a/server/src/db/models/Notification.js +++ /dev/null @@ -1,74 +0,0 @@ -import mongoose from "mongoose"; - -const NotificationSchema = mongoose.Schema( - { - userId: { - type: mongoose.Schema.Types.ObjectId, - ref: "User", - immutable: true, - required: true, - }, - teamId: { - type: mongoose.Schema.Types.ObjectId, - ref: "Team", - immutable: true, - required: true, - }, - type: { - type: String, - enum: ["email", "slack", "discord", "webhook", "pager_duty", "matrix"], - }, - notificationName: { - type: String, - required: true, - }, - address: { - type: String, - }, - phone: { - type: String, - }, - // Matrix-specific fields - homeserverUrl: { - type: String, - }, - roomId: { - type: String, - }, - accessToken: { - type: String, - }, - }, - { - timestamps: true, - } -); - -NotificationSchema.pre("save", function (next) { - if (!this.cpuAlertThreshold || this.isModified("alertThreshold")) { - this.cpuAlertThreshold = this.alertThreshold; - } - if (!this.memoryAlertThreshold || this.isModified("alertThreshold")) { - this.memoryAlertThreshold = this.alertThreshold; - } - if (!this.diskAlertThreshold || this.isModified("alertThreshold")) { - this.diskAlertThreshold = this.alertThreshold; - } - if (!this.tempAlertThreshold || this.isModified("alertThreshold")) { - this.tempAlertThreshold = this.alertThreshold; - } - next(); -}); - -NotificationSchema.pre("findOneAndUpdate", function (next) { - const update = this.getUpdate(); - if (update.alertThreshold) { - update.cpuAlertThreshold = update.alertThreshold; - update.memoryAlertThreshold = update.alertThreshold; - update.diskAlertThreshold = update.alertThreshold; - update.tempAlertThreshold = update.alertThreshold; - } - next(); -}); - -export default mongoose.model("Notification", NotificationSchema); diff --git a/server/src/db/models/Notification.ts b/server/src/db/models/Notification.ts new file mode 100755 index 000000000..97e2d43fb --- /dev/null +++ b/server/src/db/models/Notification.ts @@ -0,0 +1,50 @@ +import { Schema, model, type Types } from "mongoose"; +import type { Notification, NotificationChannel } from "@/types/notification.js"; + +interface NotificationDocument extends Omit { + _id: Types.ObjectId; + userId: Types.ObjectId; + teamId: Types.ObjectId; + createdAt: Date; + updatedAt: Date; +} + +const NotificationSchema = new Schema( + { + userId: { + type: Schema.Types.ObjectId, + ref: "User", + immutable: true, + required: true, + }, + teamId: { + type: Schema.Types.ObjectId, + ref: "Team", + immutable: true, + required: true, + }, + type: { + type: String, + enum: ["email", "slack", "discord", "webhook", "pager_duty", "matrix"] as NotificationChannel[], + required: true, + }, + notificationName: { + type: String, + required: true, + }, + address: { type: String }, + phone: { type: String }, + homeserverUrl: { type: String }, + roomId: { type: String }, + accessToken: { type: String }, + }, + { + timestamps: true, + } +); + +const NotificationModel = model("Notification", NotificationSchema); + +export type { NotificationDocument }; +export { NotificationModel }; +export default NotificationModel; diff --git a/server/src/db/models/RecoveryToken.js b/server/src/db/models/RecoveryToken.js deleted file mode 100755 index 2219a4bca..000000000 --- a/server/src/db/models/RecoveryToken.js +++ /dev/null @@ -1,25 +0,0 @@ -import mongoose from "mongoose"; - -const RecoveryTokenSchema = mongoose.Schema( - { - email: { - type: String, - required: true, - unique: true, - }, - token: { - type: String, - required: true, - }, - expiry: { - type: Date, - default: Date.now, - expires: 600, - }, - }, - { - timestamps: true, - } -); - -export default mongoose.model("RecoveryToken", RecoveryTokenSchema); diff --git a/server/src/db/models/RecoveryToken.ts b/server/src/db/models/RecoveryToken.ts new file mode 100644 index 000000000..07b697d9e --- /dev/null +++ b/server/src/db/models/RecoveryToken.ts @@ -0,0 +1,27 @@ +import { Schema, model, type Types } from "mongoose"; +import type { RecoveryToken as RecoveryTokenEntity } from "@/types/recoveryToken.js"; + +type RecoveryTokenDocumentBase = Omit & { + expiry: Date; +}; + +interface RecoveryTokenDocument extends RecoveryTokenDocumentBase { + _id: Types.ObjectId; + createdAt: Date; + updatedAt: Date; +} + +const RecoveryTokenSchema = new Schema( + { + email: { type: String, required: true, unique: true }, + token: { type: String, required: true }, + expiry: { type: Date, default: Date.now, expires: 600 }, + }, + { timestamps: true } +); + +const RecoveryTokenModel = model("RecoveryToken", RecoveryTokenSchema); + +export type { RecoveryTokenDocument }; +export { RecoveryTokenModel }; +export default RecoveryTokenModel; diff --git a/server/src/db/models/StatusPage.js b/server/src/db/models/StatusPage.js deleted file mode 100755 index 621749fb8..000000000 --- a/server/src/db/models/StatusPage.js +++ /dev/null @@ -1,85 +0,0 @@ -import mongoose from "mongoose"; - -const StatusPageSchema = mongoose.Schema( - { - userId: { - type: mongoose.Schema.Types.ObjectId, - ref: "User", - immutable: true, - required: true, - }, - teamId: { - type: mongoose.Schema.Types.ObjectId, - ref: "Team", - immutable: true, - required: true, - }, - type: { - type: String, - required: true, - default: "uptime", - enum: ["uptime"], - }, - companyName: { - type: String, - required: true, - default: "", - }, - url: { - type: String, - unique: true, - required: true, - default: "", - }, - timezone: { - type: String, - required: false, - }, - color: { - type: String, - required: false, - default: "#4169E1", - }, - monitors: [ - { - type: mongoose.Schema.Types.ObjectId, - ref: "Monitor", - required: true, - }, - ], - subMonitors: [ - { - type: mongoose.Schema.Types.ObjectId, - ref: "Monitor", - required: true, - }, - ], - logo: { - data: Buffer, - contentType: String, - }, - isPublished: { - type: Boolean, - default: false, - }, - showCharts: { - type: Boolean, - default: true, - }, - showUptimePercentage: { - type: Boolean, - default: true, - }, - showAdminLoginLink: { - type: Boolean, - default: false, - }, - customCSS: { - type: String, - default: "", - }, - }, - { timestamps: true } -); - -export default mongoose.model("StatusPage", StatusPageSchema); diff --git a/server/src/db/models/StatusPage.ts b/server/src/db/models/StatusPage.ts new file mode 100644 index 000000000..42d11bc46 --- /dev/null +++ b/server/src/db/models/StatusPage.ts @@ -0,0 +1,115 @@ +import { Schema, model, type Types } from "mongoose"; +import type { StatusPage, StatusPageLogo } from "@/types/statusPage.js"; +import { StatusPageTypes } from "@/types/statusPage.js"; + +type StatusPageDocumentBase = Omit< + StatusPage, + "id" | "userId" | "teamId" | "monitors" | "subMonitors" | "originalMonitors" | "createdAt" | "updatedAt" +> & { + monitors: Types.ObjectId[]; + subMonitors: Types.ObjectId[]; + originalMonitors?: Types.ObjectId[]; + logo?: StatusPageLogo | null; +}; + +interface StatusPageDocument extends StatusPageDocumentBase { + _id: Types.ObjectId; + userId: Types.ObjectId; + teamId: Types.ObjectId; + createdAt: Date; + updatedAt: Date; +} + +const logoSchema = new Schema( + { + data: { type: Buffer }, + contentType: { type: String }, + }, + { _id: false } +); + +const StatusPageSchema = new Schema( + { + userId: { + type: Schema.Types.ObjectId, + ref: "User", + immutable: true, + required: true, + }, + teamId: { + type: Schema.Types.ObjectId, + ref: "Team", + immutable: true, + required: true, + }, + type: { + type: String, + required: true, + default: "uptime", + enum: StatusPageTypes, + }, + companyName: { + type: String, + required: true, + default: "", + }, + url: { + type: String, + unique: true, + required: true, + default: "", + }, + timezone: { + type: String, + }, + color: { + type: String, + default: "#4169E1", + }, + monitors: [ + { + type: Schema.Types.ObjectId, + ref: "Monitor", + required: true, + }, + ], + subMonitors: [ + { + type: Schema.Types.ObjectId, + ref: "Monitor", + required: true, + }, + ], + logo: { + type: logoSchema, + default: null, + }, + isPublished: { + type: Boolean, + default: false, + }, + showCharts: { + type: Boolean, + default: true, + }, + showUptimePercentage: { + type: Boolean, + default: true, + }, + showAdminLoginLink: { + type: Boolean, + default: false, + }, + customCSS: { + type: String, + default: "", + }, + }, + { timestamps: true } +); + +const StatusPageModel = model("StatusPage", StatusPageSchema); + +export type { StatusPageDocument }; +export { StatusPageModel }; +export default StatusPageModel; diff --git a/server/src/db/models/User.js b/server/src/db/models/User.js deleted file mode 100755 index bf3012b26..000000000 --- a/server/src/db/models/User.js +++ /dev/null @@ -1,105 +0,0 @@ -import mongoose from "mongoose"; -import bcrypt from "bcryptjs"; -import Monitor from "./Monitor.js"; -import Team from "./Team.js"; -import Notification from "./Notification.js"; - -const UserSchema = mongoose.Schema( - { - firstName: { - type: String, - required: true, - }, - lastName: { - type: String, - required: true, - }, - email: { - type: String, - required: true, - unique: true, - }, - password: { - type: String, - required: true, - }, - avatarImage: { - type: String, - }, - profileImage: { - data: Buffer, - contentType: String, - }, - isActive: { - type: Boolean, - default: true, - }, - isVerified: { - type: Boolean, - default: false, - }, - role: { - type: [String], - default: "user", - enum: ["user", "admin", "superadmin", "demo"], - }, - teamId: { - type: mongoose.Schema.Types.ObjectId, - ref: "Team", - immutable: true, - }, - checkTTL: { - type: Number, - }, - }, - { - timestamps: true, - } -); - -UserSchema.pre("save", function (next) { - if (!this.isModified("password")) { - return next(); - } - const salt = bcrypt.genSaltSync(10); - this.password = bcrypt.hashSync(this.password, salt); - next(); -}); - -UserSchema.pre("findOneAndUpdate", function (next) { - const update = this.getUpdate(); - if ("password" in update) { - const salt = bcrypt.genSaltSync(10); - update.password = bcrypt.hashSync(update.password, salt); - } - - next(); -}); - -UserSchema.pre("findOneAndDelete", async function (next) { - try { - const userToDelete = await this.model.findOne(this.getFilter()); - if (!userToDelete) return next(); - if (userToDelete.role.includes("superadmin")) { - await Team.deleteOne({ _id: userToDelete.teamId }); - await Monitor.deleteMany({ userId: userToDelete._id }); - await this.model.deleteMany({ - teamId: userToDelete.teamId, - _id: { $ne: userToDelete._id }, - }); - await Notification.deleteMany({ teamId: userToDelete.teamId }); - } - next(); - } catch (error) { - next(error); - } -}); - -UserSchema.methods.comparePassword = async function (submittedPassword) { - const res = await bcrypt.compare(submittedPassword, this.password); - return res; -}; - -const User = mongoose.model("User", UserSchema); - -export default User; diff --git a/server/src/db/models/User.ts b/server/src/db/models/User.ts new file mode 100644 index 000000000..6aa3835a6 --- /dev/null +++ b/server/src/db/models/User.ts @@ -0,0 +1,95 @@ +import { Schema, model, type Types } from "mongoose"; +import bcrypt from "bcryptjs"; +import type { User, UserProfileImage, UserRole } from "@/types/index.js"; +import { MonitorModel } from "@/db/models/index.js"; +import Team from "./Team.js"; +import NotificationModel from "./Notification.js"; + +type UserDocumentBase = Omit & { + teamId?: Types.ObjectId; + profileImage?: Required; +}; + +interface UserDocument extends UserDocumentBase { + _id: Types.ObjectId; + teamId?: Types.ObjectId; + createdAt: Date; + updatedAt: Date; +} + +const profileImageSchema = new Schema>( + { + data: { type: Buffer }, + contentType: { type: String }, + }, + { _id: false } +); + +const UserSchema = new Schema( + { + firstName: { type: String, required: true }, + lastName: { type: String, required: true }, + email: { type: String, required: true, unique: true }, + password: { type: String, required: true }, + avatarImage: { type: String }, + profileImage: { type: profileImageSchema }, + isActive: { type: Boolean, default: true }, + isVerified: { type: Boolean, default: false }, + role: { + type: [String], + enum: ["user", "admin", "superadmin", "demo" satisfies UserRole], + default: ["user"], + }, + teamId: { + type: Schema.Types.ObjectId, + ref: "Team", + immutable: true, + }, + checkTTL: { type: Number }, + }, + { timestamps: true } +); + +UserSchema.pre("save", function (next) { + if (!this.isModified("password")) { + return next(); + } + const salt = bcrypt.genSaltSync(10); + this.password = bcrypt.hashSync(this.password, salt); + next(); +}); + +UserSchema.pre("findOneAndUpdate", function (next) { + const update = this.getUpdate(); + if (update && "password" in update) { + const salt = bcrypt.genSaltSync(10); + (update as any).password = bcrypt.hashSync((update as any).password, salt); + } + next(); +}); + +UserSchema.pre("findOneAndDelete", async function (next) { + try { + const userToDelete = await this.model.findOne(this.getFilter()); + if (!userToDelete) return next(); + if (userToDelete.role.includes("superadmin")) { + await Team.deleteOne({ _id: userToDelete.teamId }); + await MonitorModel.deleteMany({ userId: userToDelete._id }); + await this.model.deleteMany({ teamId: userToDelete.teamId, _id: { $ne: userToDelete._id } }); + await NotificationModel.deleteMany({ teamId: userToDelete.teamId }); + } + next(); + } catch (error) { + next(error as Error); + } +}); + +UserSchema.methods.comparePassword = async function (submittedPassword: string) { + return bcrypt.compare(submittedPassword, this.password); +}; + +const UserModel = model("User", UserSchema); + +export type { UserDocument }; +export { UserModel }; +export default UserModel; diff --git a/server/src/db/models/index.ts b/server/src/db/models/index.ts index 3ac99a390..4b71937bb 100644 --- a/server/src/db/models/index.ts +++ b/server/src/db/models/index.ts @@ -6,3 +6,24 @@ export { default as CheckModel } from "@/db/models/Check.js"; export * from "@/db/models/MonitorStats.js"; export { default as MonitorStatsModel } from "@/db/models/MonitorStats.js"; + +export * from "@/db/models/StatusPage.js"; +export { default as StatusPageModel } from "@/db/models/StatusPage.js"; + +export * from "@/db/models/User.js"; +export { default as UserModel } from "@/db/models/User.js"; + +export * from "@/db/models/Invite.js"; +export { default as InviteModel } from "@/db/models/Invite.js"; + +export * from "@/db/models/AppSettings.js"; +export { default as AppSettingsModel } from "@/db/models/AppSettings.js"; + +export * from "@/db/models/RecoveryToken.js"; +export { default as RecoveryTokenModel } from "@/db/models/RecoveryToken.js"; + +export * from "@/db/models/Notification.js"; +export { default as NotificationModel } from "@/db/models/Notification.js"; + +export * from "@/db/models/Incident.js"; +export { default as IncidentModel } from "@/db/models/Incident.js"; diff --git a/server/src/db/modules/checkModule.js b/server/src/db/modules/checkModule.js deleted file mode 100755 index e420d5ce7..000000000 --- a/server/src/db/modules/checkModule.js +++ /dev/null @@ -1,290 +0,0 @@ -import { ObjectId } from "mongodb"; -import mongoose from "mongoose"; -import { CheckModel } from "@/db/models/index.js"; -import { buildChecksSummaryByTeamIdPipeline } from "./checkModuleQueries.js"; - -const SERVICE_NAME = "checkModule"; -const dateRangeLookup = { - recent: new Date(new Date().setDate(new Date().getDate() - 2)), - hour: new Date(new Date().setHours(new Date().getHours() - 1)), - day: new Date(new Date().setDate(new Date().getDate() - 1)), - week: new Date(new Date().setDate(new Date().getDate() - 7)), - month: new Date(new Date().setMonth(new Date().getMonth() - 1)), - all: undefined, -}; - -class CheckModule { - constructor({ logger, Monitor, User }) { - this.logger = logger; - this.Monitor = Monitor; - this.User = User; - } - - createChecks = async (checks) => { - try { - await CheckModel.insertMany(checks, { ordered: false, runValidators: true }); - } catch (error) { - error.service = SERVICE_NAME; - error.method = "createCheck"; - throw error; - } - }; - - getChecksByMonitor = async ({ monitorId, sortOrder, dateRange, filter, ack, page, rowsPerPage, status }) => { - try { - status = status === "true" ? true : status === "false" ? false : undefined; - page = parseInt(page); - rowsPerPage = parseInt(rowsPerPage); - - const ackStage = ack === "true" ? { ack: true } : { $or: [{ ack: false }, { ack: { $exists: false } }] }; - - // Match - const matchStage = { - "metadata.monitorId": new ObjectId(monitorId), - ...(typeof status !== "undefined" && { status }), - ...(typeof ack !== "undefined" && ackStage), - ...(dateRangeLookup[dateRange] && { - createdAt: { - $gte: dateRangeLookup[dateRange], - }, - }), - }; - - if (filter !== undefined) { - switch (filter) { - case "all": - break; - case "down": - break; - case "resolve": - matchStage.statusCode = 5000; - break; - default: - this.logger.warn({ - message: "invalid filter", - service: SERVICE_NAME, - method: "getChecks", - }); - break; - } - } - - //Sort - sortOrder = sortOrder === "asc" ? 1 : -1; - - // Pagination - let skip = 0; - if (page && rowsPerPage) { - skip = page * rowsPerPage; - } - - const checks = await CheckModel.aggregate([ - { $match: matchStage }, - { $sort: { createdAt: sortOrder } }, - { - $facet: { - summary: [{ $count: "checksCount" }], - checks: [{ $skip: skip }, { $limit: rowsPerPage }], - }, - }, - { - $project: { - checksCount: { - $ifNull: [{ $arrayElemAt: ["$summary.checksCount", 0] }, 0], - }, - checks: { - $ifNull: ["$checks", []], - }, - }, - }, - ]); - return checks[0]; - } catch (error) { - error.service = SERVICE_NAME; - error.method = "getChecks"; - throw error; - } - }; - - getChecksByTeam = async ({ sortOrder, dateRange, filter, ack, page, rowsPerPage, teamId }) => { - try { - page = parseInt(page); - rowsPerPage = parseInt(rowsPerPage); - - const ackStage = ack === "true" ? { ack: true } : { $or: [{ ack: false }, { ack: { $exists: false } }] }; - - const matchStage = { - "metadata.teamId": new ObjectId(teamId), - status: false, - ...(typeof ack !== "undefined" && ackStage), - ...(dateRangeLookup[dateRange] && { - createdAt: { - $gte: dateRangeLookup[dateRange], - }, - }), - }; - // Add filter to match stage - if (filter !== undefined) { - switch (filter) { - case "all": - break; - case "down": - break; - case "resolve": - matchStage.statusCode = 5000; - break; - default: - this.logger.warn({ - message: "invalid filter", - service: SERVICE_NAME, - method: "getChecksByTeam", - }); - break; - } - } - - sortOrder = sortOrder === "asc" ? 1 : -1; - - // pagination - let skip = 0; - if (page && rowsPerPage) { - skip = page * rowsPerPage; - } - - const aggregatePipeline = [ - { $match: matchStage }, - - { $sort: { createdAt: sortOrder } }, - { - $facet: { - summary: [{ $count: "checksCount" }], - checks: [{ $skip: skip }, { $limit: rowsPerPage }], - }, - }, - { - $project: { - checksCount: { $arrayElemAt: ["$summary.checksCount", 0] }, - checks: "$checks", - }, - }, - ]; - - const checks = await CheckModel.aggregate(aggregatePipeline); - return checks[0]; - } catch (error) { - error.service = SERVICE_NAME; - error.method = "getChecksByTeam"; - throw error; - } - }; - - ackCheck = async (checkId, teamId, ack) => { - try { - const updatedCheck = await CheckModel.findOneAndUpdate( - { _id: checkId, "metadata.teamId": teamId }, - { $set: { ack, ackAt: new Date() } }, - { new: true } - ); - - if (!updatedCheck) { - throw new Error("Check not found"); - } - - return updatedCheck; - } catch (error) { - error.service = SERVICE_NAME; - error.method = "ackCheck"; - throw error; - } - }; - - ackAllChecks = async (monitorId, teamId, ack, path) => { - try { - const filter = - path === "monitor" - ? { "metadata.monitorId": new mongoose.Types.ObjectId(monitorId) } - : { "metadata.teamId": new mongoose.Types.ObjectId(teamId) }; - const updatedChecks = await CheckModel.updateMany(filter, { $set: { ack, ackAt: new Date() } }); - return updatedChecks.modifiedCount; - } catch (error) { - error.service = SERVICE_NAME; - error.method = "ackAllChecks"; - throw error; - } - }; - - getChecksSummaryByTeamId = async ({ teamId }) => { - try { - const matchStage = { - "metadata.teamId": new ObjectId(teamId), - }; - const checks = await CheckModel.aggregate(buildChecksSummaryByTeamIdPipeline({ matchStage })); - return checks[0].summary; - } catch (error) { - error.service = SERVICE_NAME; - error.method = "getChecksSummaryByTeamId"; - throw error; - } - }; - deleteChecks = async (monitorId) => { - try { - const result = await CheckModel.deleteMany({ "metadata.monitorId": monitorId }); - return result.deletedCount; - } catch (error) { - error.service = SERVICE_NAME; - error.method = "deleteChecks"; - throw error; - } - }; - - deleteChecksByTeamId = async (teamId) => { - try { - // Find all monitor IDs for this team (only get _id field for efficiency) - const teamMonitors = await this.Monitor.find({ teamId }, { _id: 1 }); - const monitorIds = teamMonitors.map((monitor) => monitor._id); - - // Delete all checks for these monitors in one operation - const deleteResult = await CheckModel.deleteMany({ "metadata.monitorId": { $in: monitorIds } }); - - return deleteResult.deletedCount; - } catch (error) { - error.service = SERVICE_NAME; - error.method = "deleteChecksByTeamId"; - throw error; - } - }; - - updateChecksTTL = async (teamId, ttl) => { - try { - await CheckModel.collection.dropIndex("expiry_1"); - } catch (error) { - this.logger.error({ - message: error.message, - service: SERVICE_NAME, - method: "updateChecksTTL", - stack: error.stack, - }); - } - - try { - await CheckModel.collection.createIndex( - { expiry: 1 }, - { expireAfterSeconds: ttl, partialFilterExpression: { "metadata.mode": { $exists: true } } } - ); - } catch (error) { - error.service = SERVICE_NAME; - error.method = "updateChecksTTL"; - throw error; - } - // Update user - try { - await this.User.updateMany({ teamId: teamId }, { checkTTL: ttl }); - } catch (error) { - error.service = SERVICE_NAME; - error.method = "updateChecksTTL"; - throw error; - } - }; -} - -export default CheckModule; diff --git a/server/src/db/modules/checkModuleQueries.js b/server/src/db/modules/checkModuleQueries.js deleted file mode 100644 index f2ad2a922..000000000 --- a/server/src/db/modules/checkModuleQueries.js +++ /dev/null @@ -1,44 +0,0 @@ -const buildChecksSummaryByTeamIdPipeline = ({ matchStage }) => { - return [ - { $match: matchStage }, - { - $facet: { - summary: [ - { - $group: { - _id: null, - totalChecks: { $sum: { $cond: [{ $eq: ["$status", false] }, 1, 0] } }, - resolvedChecks: { - $sum: { - $cond: [{ $and: [{ $eq: ["$ack", true] }, { $eq: ["$status", false] }] }, 1, 0], - }, - }, - downChecks: { - $sum: { - $cond: [{ $and: [{ $eq: ["$ack", false] }, { $eq: ["$status", false] }] }, 1, 0], - }, - }, - cannotResolveChecks: { - $sum: { - $cond: [{ $eq: ["$statusCode", 5000] }, 1, 0], - }, - }, - }, - }, - { - $project: { - _id: 0, - }, - }, - ], - }, - }, - { - $project: { - summary: { $arrayElemAt: ["$summary", 0] }, - }, - }, - ]; -}; - -export { buildChecksSummaryByTeamIdPipeline }; diff --git a/server/src/db/modules/monitorModule.js b/server/src/db/modules/monitorModule.js deleted file mode 100755 index 84ff86996..000000000 --- a/server/src/db/modules/monitorModule.js +++ /dev/null @@ -1,540 +0,0 @@ -import { - buildUptimeDetailsPipeline, - buildMonitorSummaryByTeamIdPipeline, - buildMonitorsByTeamIdPipeline, - buildMonitorsAndSummaryByTeamIdPipeline, - buildMonitorsWithChecksByTeamIdPipeline, - buildFilteredMonitorsByTeamIdPipeline, - getHardwareStats, - getUpChecks, - getAggregateData, -} from "./monitorModuleQueries.js"; - -import { CheckModel } from "@/db/models/index.js"; - -const SERVICE_NAME = "monitorModule"; - -class MonitorModule { - constructor({ Monitor, MonitorStats, stringService, fs, path, fileURLToPath, ObjectId, NormalizeData, NormalizeDataUptimeDetails }) { - this.Monitor = Monitor; - this.MonitorStats = MonitorStats; - this.stringService = stringService; - this.fs = fs; - this.path = path; - this.fileURLToPath = fileURLToPath; - this.ObjectId = ObjectId; - this.NormalizeData = NormalizeData; - this.NormalizeDataUptimeDetails = NormalizeDataUptimeDetails; - - const __filename = fileURLToPath(import.meta.url); - const __dirname = path.dirname(__filename); - - this.demoMonitorsPath = path.resolve(__dirname, "../../../utils/demoMonitors.json"); - } - - // Helper - calculateUptimeDuration = (checks) => { - if (!checks || checks.length === 0) { - return 0; - } - const latestCheck = new Date(checks[0].createdAt); - let latestDownCheck = 0; - - for (let i = checks.length - 1; i >= 0; i--) { - if (checks[i].status === false) { - latestDownCheck = new Date(checks[i].createdAt); - break; - } - } - - // If no down check is found, uptime is from the last check to now - if (latestDownCheck === 0) { - return Date.now() - new Date(checks[checks.length - 1].createdAt); - } - - // Otherwise the uptime is from the last check to the last down check - return latestCheck - latestDownCheck; - }; - - // Helper - getLastChecked = (checks) => { - if (!checks || checks.length === 0) { - return 0; // Handle case when no checks are available - } - // Data is sorted newest->oldest, so last check is the most recent - return new Date() - new Date(checks[0].createdAt); - }; - getLatestResponseTime = (checks) => { - if (!checks || checks.length === 0) { - return 0; - } - - return checks[0]?.responseTime ?? 0; - }; - - // Helper - getAverageResponseTime = (checks) => { - if (!checks || checks.length === 0) { - return 0; - } - - const validChecks = checks.filter((check) => typeof check.responseTime === "number"); - if (validChecks.length === 0) { - return 0; - } - const aggResponseTime = validChecks.reduce((sum, check) => { - return sum + check.responseTime; - }, 0); - return aggResponseTime / validChecks.length; - }; - - // Helper - getUptimePercentage = (checks) => { - if (!checks || checks.length === 0) { - return 0; - } - const upCount = checks.reduce((count, check) => { - return check.status === true ? count + 1 : count; - }, 0); - return (upCount / checks.length) * 100; - }; - - // Helper - getIncidents = (checks) => { - if (!checks || checks.length === 0) { - return 0; // Handle case when no checks are available - } - return checks.reduce((acc, check) => { - return check.status === false ? (acc += 1) : acc; - }, 0); - }; - - // Helper - getDateRange = (dateRange) => { - const startDates = { - recent: new Date(new Date().setHours(new Date().getHours() - 2)), - day: new Date(new Date().setDate(new Date().getDate() - 1)), - week: new Date(new Date().setDate(new Date().getDate() - 7)), - month: new Date(new Date().setMonth(new Date().getMonth() - 1)), - all: new Date(0), - }; - return { - start: startDates[dateRange], - end: new Date(), - }; - }; - - //Helper - getMonitorChecks = async (monitorId, dateRange, sortOrder) => { - const objectId = new this.ObjectId(monitorId); - const indexSpec = { - "metadata.monitorId": 1, - updatedAt: sortOrder, - }; - - const matchBase = { "metadata.monitorId": objectId }; - - const [checksAll, checksForDateRange] = await Promise.all([ - CheckModel.find(matchBase).sort({ createdAt: sortOrder }).hint(indexSpec).lean(), - CheckModel.find({ - ...matchBase, - createdAt: { $gte: dateRange.start, $lte: dateRange.end }, - }) - .hint(indexSpec) - .lean(), - ]); - - return { checksAll, checksForDateRange }; - }; - - // Helper - processChecksForDisplay = (normalizeData, checks, numToDisplay, normalize) => { - let processedChecks = checks; - if (numToDisplay && checks.length > numToDisplay) { - const n = Math.ceil(checks.length / numToDisplay); - processedChecks = checks.filter((_, index) => index % n === 0); - } - return normalize ? normalizeData(processedChecks, 1, 100) : processedChecks; - }; - - // Helper - groupChecksByTime = (checks, dateRange) => { - return checks.reduce((acc, check) => { - // Validate the date - const checkDate = new Date(check.createdAt); - if (Number.isNaN(checkDate.getTime()) || checkDate.getTime() === 0) { - return acc; - } - - const time = dateRange === "day" ? checkDate.setMinutes(0, 0, 0) : checkDate.toISOString().split("T")[0]; - - if (!acc[time]) { - acc[time] = { time, checks: [] }; - } - acc[time].checks.push(check); - return acc; - }, {}); - }; - - // Helper - calculateGroupStats = (group) => { - const totalChecks = group.checks.length; - - const checksWithResponseTime = group.checks.filter((check) => typeof check.responseTime === "number" && !Number.isNaN(check.responseTime)); - - return { - time: group.time, - uptimePercentage: this.getUptimePercentage(group.checks), - totalChecks, - totalIncidents: group.checks.filter((check) => !check.status).length, - avgResponseTime: - checksWithResponseTime.length > 0 - ? checksWithResponseTime.reduce((sum, check) => sum + check.responseTime, 0) / checksWithResponseTime.length - : 0, - }; - }; - - getMonitorById = async (monitorId) => { - try { - const monitor = await this.Monitor.findById(monitorId); - if (monitor === null || monitor === undefined) { - const error = new Error(this.stringService.getDbFindMonitorById(monitorId)); - error.status = 404; - throw error; - } - - return monitor; - } catch (error) { - error.service = SERVICE_NAME; - error.method = "getMonitorById"; - throw error; - } - }; - - getMonitorsByIds = async (monitorIds) => { - try { - const objectIds = monitorIds.map((id) => new this.ObjectId(id)); - return await this.Monitor.find({ _id: { $in: objectIds } }, { _id: 1, teamId: 1 }).lean(); - } catch (error) { - error.service = SERVICE_NAME; - error.method = "getMonitorsByIds"; - throw error; - } - }; - getUptimeDetailsById = async ({ monitorId, dateRange }) => { - try { - const dates = this.getDateRange(dateRange); - const formatLookup = { - recent: "%Y-%m-%dT%H:%M:00Z", - day: "%Y-%m-%dT%H:00:00Z", - week: "%Y-%m-%dT00:00:00Z", - month: "%Y-%m-%dT00:00:00Z", - }; - - const dateString = formatLookup[dateRange]; - - const results = await CheckModel.aggregate(buildUptimeDetailsPipeline(monitorId, dates, dateString)); - - const monitorData = results[0]; - - monitorData.groupedUpChecks = this.NormalizeDataUptimeDetails(monitorData.groupedUpChecks, 10, 100); - - monitorData.groupedDownChecks = this.NormalizeDataUptimeDetails(monitorData.groupedDownChecks, 10, 100); - - const normalizedGroupChecks = this.NormalizeDataUptimeDetails(monitorData.groupedChecks, 10, 100); - - monitorData.groupedChecks = normalizedGroupChecks; - const monitorStats = await this.MonitorStats.findOne({ monitorId }); - return { monitorData, monitorStats }; - } catch (error) { - error.service = SERVICE_NAME; - error.method = "getUptimeDetailsById"; - throw error; - } - }; - - getHardwareDetailsById = async ({ monitorId, dateRange }) => { - try { - const monitor = await this.Monitor.findById(monitorId); - const dates = this.getDateRange(dateRange); - - const formatLookup = { - recent: "%Y-%m-%dT%H:%M:00Z", - day: "%Y-%m-%dT%H:00:00Z", - week: "%Y-%m-%dT00:00:00Z", - month: "%Y-%m-%dT00:00:00Z", - }; - const dateString = formatLookup[dateRange]; - - const [aggregateData, upChecksCount, metrics] = await Promise.all([ - getAggregateData(monitorId, dates), - getUpChecks(monitorId, dates), - getHardwareStats(monitorId, dates, dateString), - ]); - - const stats = { - aggregateData: aggregateData, - upChecks: upChecksCount, - checks: metrics, - }; - - return { - ...monitor.toObject(), - stats, - }; - } catch (error) { - error.service = SERVICE_NAME; - error.method = "getHardwareDetailsById"; - throw error; - } - }; - - getMonitorsByTeamId = async ({ teamId, type, filter }) => { - try { - const matchStage = { teamId: new this.ObjectId(teamId) }; - if (type !== undefined) { - matchStage.type = Array.isArray(type) ? { $in: type } : type; - } - if (filter !== undefined && filter !== null && filter !== "") { - matchStage.$or = [{ name: { $regex: filter, $options: "i" } }, { url: { $regex: filter, $options: "i" } }]; - } - const monitors = await this.Monitor.find(matchStage) - .sort({ name: 1 }) - .select({ - _id: 1, - name: 1, - type: 1, - url: 1, - status: 1, - isActive: 1, - teamId: 1, - }) - .lean(); - return monitors; - } catch (error) { - error.service = SERVICE_NAME; - error.method = "getMonitorsByTeamId"; - throw error; - } - }; - - getMonitorsAndSummaryByTeamId = async ({ type, explain, teamId }) => { - try { - const matchStage = { teamId: new this.ObjectId(teamId) }; - if (type !== undefined) { - matchStage.type = Array.isArray(type) ? { $in: type } : type; - } - - if (explain === true) { - return this.Monitor.aggregate(buildMonitorsAndSummaryByTeamIdPipeline({ matchStage })).explain("executionStats"); - } - - const queryResult = await this.Monitor.aggregate(buildMonitorsAndSummaryByTeamIdPipeline({ matchStage })); - const { monitors, summary } = queryResult?.[0] ?? {}; - return { monitors, summary }; - } catch (error) { - error.service = SERVICE_NAME; - error.method = "getMonitorsAndSummaryByTeamId"; - throw error; - } - }; - - getMonitorsWithChecksByTeamId = async ({ limit, type, page, rowsPerPage, filter, field, order, teamId, explain }) => { - try { - limit = parseInt(limit); - page = parseInt(page); - rowsPerPage = parseInt(rowsPerPage); - if (field === undefined) { - field = "name"; - order = "asc"; - } - // Build match stage - const matchStage = { teamId: new this.ObjectId(teamId) }; - if (type !== undefined) { - matchStage.type = Array.isArray(type) ? { $in: type } : type; - } - - if (explain === true) { - return this.Monitor.aggregate( - buildMonitorsWithChecksByTeamIdPipeline({ - matchStage, - filter, - page, - rowsPerPage, - field, - order, - limit, - type, - }) - ).explain("executionStats"); - } - - const queryResult = await this.Monitor.aggregate( - buildMonitorsWithChecksByTeamIdPipeline({ - matchStage, - filter, - page, - rowsPerPage, - field, - order, - limit, - type, - }) - ); - const monitors = queryResult[0]?.monitors; - const count = queryResult[0]?.count; - const normalizedFilteredMonitors = monitors.map((monitor) => { - if (!monitor.checks) { - return monitor; - } - monitor.checks = this.NormalizeData(monitor.checks, 10, 100); - return monitor; - }); - return { count, monitors: normalizedFilteredMonitors }; - } catch (error) { - error.service = SERVICE_NAME; - error.method = "getMonitorsWithChecksByTeamId"; - throw error; - } - }; - createMonitor = async ({ body, teamId, userId }) => { - try { - const monitor = new this.Monitor({ ...body, teamId, userId }); - const saved = await monitor.save(); - return saved; - } catch (error) { - error.service = SERVICE_NAME; - error.method = "createMonitor"; - throw error; - } - }; - - createBulkMonitors = async (req) => { - try { - const monitors = req.map((item) => new this.Monitor({ ...item, notifications: undefined })); - await this.Monitor.bulkSave(monitors); - return monitors; - } catch (error) { - error.service = SERVICE_NAME; - error.method = "createBulkMonitors"; - throw error; - } - }; - - deleteMonitor = async ({ teamId, monitorId }) => { - try { - const deletedMonitor = await this.Monitor.findOneAndDelete({ _id: monitorId, teamId }); - - if (!deletedMonitor) { - throw new Error(this.stringService.getDbFindMonitorById(monitorId)); - } - - return deletedMonitor; - } catch (error) { - error.service = SERVICE_NAME; - error.method = "deleteMonitor"; - throw error; - } - }; - - deleteAllMonitors = async (teamId) => { - try { - const monitors = await this.Monitor.find({ teamId }); - const { deletedCount } = await this.Monitor.deleteMany({ teamId }); - - return { monitors, deletedCount }; - } catch (error) { - error.service = SERVICE_NAME; - error.method = "deleteAllMonitors"; - throw error; - } - }; - - deleteMonitorsByUserId = async (userId) => { - try { - const result = await this.Monitor.deleteMany({ userId: userId }); - return result; - } catch (error) { - error.service = SERVICE_NAME; - error.method = "deleteMonitorsByUserId"; - throw error; - } - }; - - editMonitor = async ({ monitorId, body }) => { - try { - const editedMonitor = await this.Monitor.findByIdAndUpdate(monitorId, body, { - new: true, - }); - return editedMonitor; - } catch (error) { - error.service = SERVICE_NAME; - error.method = "editMonitor"; - throw error; - } - }; - - addDemoMonitors = async (userId, teamId) => { - try { - const demoMonitors = JSON.parse(this.fs.readFileSync(this.demoMonitorsPath, "utf8")); - - const demoMonitorsToInsert = demoMonitors.map((monitor) => { - return { - userId, - teamId, - name: monitor.name, - description: monitor.name, - type: "http", - url: monitor.url, - interval: 60000, - }; - }); - const insertedMonitors = await this.Monitor.insertMany(demoMonitorsToInsert); - return insertedMonitors; - } catch (error) { - error.service = SERVICE_NAME; - error.method = "addDemoMonitors"; - throw error; - } - }; - - pauseMonitor = async ({ monitorId }) => { - try { - const monitor = await this.Monitor.findOneAndUpdate( - { _id: monitorId }, - [ - { - $set: { - isActive: { $not: "$isActive" }, - status: "$$REMOVE", - }, - }, - ], - { new: true } - ); - - return monitor; - } catch (error) { - error.service = SERVICE_NAME; - error.method = "pauseMonitor"; - throw error; - } - }; - - getGroupsByTeamId = async ({ teamId }) => { - try { - const groups = await this.Monitor.distinct("group", { - teamId: new this.ObjectId(teamId), - group: { $ne: null, $ne: "" }, - }); - - return groups.filter(Boolean).sort(); - } catch (error) { - error.service = SERVICE_NAME; - error.method = "getGroupsByTeamId"; - throw error; - } - }; -} - -export default MonitorModule; diff --git a/server/src/db/modules/monitorModuleQueries.js b/server/src/db/modules/monitorModuleQueries.js deleted file mode 100755 index 596f11791..000000000 --- a/server/src/db/modules/monitorModuleQueries.js +++ /dev/null @@ -1,740 +0,0 @@ -import { ObjectId } from "mongodb"; -import { CheckModel } from "@/db/models/index.js"; - -const buildUptimeDetailsPipeline = (monitorId, dates, dateString) => { - return [ - { - $match: { - "metadata.monitorId": new ObjectId(monitorId), - updatedAt: { $gte: dates.start, $lte: dates.end }, - }, - }, - { - $sort: { - updatedAt: 1, - }, - }, - { - $facet: { - // For the response time chart, should return checks for date window - // Grouped by: {day: hour}, {week: day}, {month: day} - uptimePercentage: [ - { - $group: { - _id: null, - upChecks: { - $sum: { $cond: [{ $eq: ["$status", true] }, 1, 0] }, - }, - totalChecks: { $sum: 1 }, - }, - }, - { - $project: { - _id: 0, - percentage: { - $cond: [{ $eq: ["$totalChecks", 0] }, 0, { $divide: ["$upChecks", "$totalChecks"] }], - }, - }, - }, - ], - groupedAvgResponseTime: [ - { - $group: { - _id: null, - avgResponseTime: { - $avg: "$responseTime", - }, - }, - }, - ], - groupedChecks: [ - { - $group: { - _id: { - $dateToString: { - format: dateString, - date: "$createdAt", - }, - }, - avgResponseTime: { - $avg: "$responseTime", - }, - totalChecks: { - $sum: 1, - }, - }, - }, - { - $sort: { - _id: 1, - }, - }, - ], - // Up checks grouped by: {day: hour}, {week: day}, {month: day} - groupedUpChecks: [ - { - $match: { - status: true, - }, - }, - { - $group: { - _id: { - $dateToString: { - format: dateString, - date: "$createdAt", - }, - }, - totalChecks: { - $sum: 1, - }, - avgResponseTime: { - $avg: "$responseTime", - }, - }, - }, - { - $sort: { _id: 1 }, - }, - ], - // Down checks grouped by: {day: hour}, {week: day}, {month: day} for the date window - groupedDownChecks: [ - { - $match: { - status: false, - }, - }, - { - $group: { - _id: { - $dateToString: { - format: dateString, - date: "$createdAt", - }, - }, - totalChecks: { - $sum: 1, - }, - avgResponseTime: { - $avg: "$responseTime", - }, - }, - }, - { - $sort: { _id: 1 }, - }, - ], - }, - }, - { - $lookup: { - from: "monitors", - let: { monitor_id: { $toObjectId: monitorId } }, - pipeline: [ - { - $match: { - $expr: { $eq: ["$_id", "$$monitor_id"] }, - }, - }, - { - $project: { - _id: 1, - teamId: 1, - name: 1, - status: 1, - interval: 1, - type: 1, - url: 1, - isActive: 1, - notifications: 1, - }, - }, - ], - as: "monitor", - }, - }, - { - $project: { - groupedAvgResponseTime: { - $arrayElemAt: ["$groupedAvgResponseTime.avgResponseTime", 0], - }, - - groupedChecks: "$groupedChecks", - groupedUpChecks: "$groupedUpChecks", - groupedDownChecks: "$groupedDownChecks", - groupedUptimePercentage: { $arrayElemAt: ["$uptimePercentage.percentage", 0] }, - monitor: { $arrayElemAt: ["$monitor", 0] }, - }, - }, - ]; -}; - -const buildMonitorStatsPipeline = (monitor) => { - return [ - { - $match: { - monitorId: monitor._id, - }, - }, - { - $project: { - avgResponseTime: 1, - uptimePercentage: 1, - totalChecks: 1, - timeSinceLastCheck: { - $subtract: [Date.now(), "$lastCheckTimestamp"], - }, - lastCheckTimestamp: 1, - uptBurnt: { $toString: "$uptBurnt" }, - }, - }, - ]; -}; - -const buildMonitorSummaryByTeamIdPipeline = ({ matchStage }) => { - return [ - { $match: matchStage }, - { - $group: { - _id: null, - totalMonitors: { $sum: 1 }, - upMonitors: { - $sum: { - $cond: [{ $eq: ["$status", true] }, 1, 0], - }, - }, - downMonitors: { - $sum: { - $cond: [{ $eq: ["$status", false] }, 1, 0], - }, - }, - pausedMonitors: { - $sum: { - $cond: [{ $eq: ["$isActive", false] }, 1, 0], - }, - }, - }, - }, - { - $project: { - _id: 0, - }, - }, - ]; -}; - -const buildMonitorsByTeamIdPipeline = ({ matchStage, field, order }) => { - const sort = { [field]: order === "asc" ? 1 : -1 }; - - return [ - { $match: matchStage }, - { $sort: sort }, - { - $project: { - _id: 1, - name: 1, - type: 1, - port: 1, - }, - }, - ]; -}; - -const buildMonitorsAndSummaryByTeamIdPipeline = ({ matchStage }) => { - return [ - { $match: matchStage }, - { - $facet: { - summary: [ - { - $group: { - _id: null, - totalMonitors: { $sum: 1 }, - upMonitors: { - $sum: { - $cond: [{ $eq: ["$status", true] }, 1, 0], - }, - }, - downMonitors: { - $sum: { - $cond: [{ $eq: ["$status", false] }, 1, 0], - }, - }, - pausedMonitors: { - $sum: { - $cond: [{ $eq: ["$isActive", false] }, 1, 0], - }, - }, - }, - }, - { - $project: { - _id: 0, - }, - }, - ], - monitors: [ - { $sort: { name: 1 } }, - { - $project: { - _id: 1, - name: 1, - type: 1, - }, - }, - ], - }, - }, - { - $project: { - summary: { $arrayElemAt: ["$summary", 0] }, - monitors: 1, - }, - }, - ]; -}; - -const buildMonitorsWithChecksByTeamIdPipeline = ({ matchStage, filter, page, rowsPerPage, field, order, limit, type }) => { - const skip = page && rowsPerPage ? page * rowsPerPage : 0; - const sort = { [field]: order === "asc" ? 1 : -1 }; - const limitStage = rowsPerPage ? [{ $limit: rowsPerPage }] : []; - - // Match name - if (typeof filter !== "undefined" && field === "name") { - matchStage.$or = [{ name: { $regex: filter, $options: "i" } }, { url: { $regex: filter, $options: "i" } }]; - } - - // Match isActive - if (typeof filter !== "undefined" && field === "isActive") { - matchStage.isActive = filter === "true" ? true : false; - } - - if (typeof filter !== "undefined" && field === "status") { - matchStage.status = filter === "true" ? true : false; - } - - // Match type - if (typeof filter !== "undefined" && field === "type") { - matchStage.type = filter; - } - - const monitorsPipeline = [ - { $sort: sort }, - { $skip: skip }, - ...limitStage, - { - $project: { - _id: 1, - name: 1, - description: 1, - type: 1, - url: 1, - isActive: 1, - createdAt: 1, - updatedAt: 1, - uptimePercentage: 1, - status: 1, - }, - }, - ]; - - // Add checks - if (limit) { - const checksCollection = "checks"; - monitorsPipeline.push({ - $lookup: { - from: checksCollection, - let: { monitorId: "$_id" }, - pipeline: [ - { - $match: { - $expr: { $eq: ["$monitorId", "$$monitorId"] }, - }, - }, - { $sort: { updatedAt: -1 } }, - { $limit: limit }, - { - $project: { - _id: 1, - status: 1, - responseTime: 1, - statusCode: 1, - createdAt: 1, - updatedAt: 1, - originalResponseTime: 1, - }, - }, - ], - as: "checks", - }, - }); - } - - const pipeline = [ - { $match: matchStage }, - { - $facet: { - count: [{ $count: "monitorsCount" }], - monitors: monitorsPipeline, - }, - }, - { - $project: { - count: { $arrayElemAt: ["$count", 0] }, - monitors: 1, - }, - }, - ]; - return pipeline; -}; - -const buildFilteredMonitorsByTeamIdPipeline = ({ matchStage, filter, page, rowsPerPage, field, order, limit, type }) => { - const skip = page && rowsPerPage ? page * rowsPerPage : 0; - const sort = { [field]: order === "asc" ? 1 : -1 }; - const limitStage = rowsPerPage ? [{ $limit: rowsPerPage }] : []; - - if (typeof filter !== "undefined" && field === "name") { - matchStage.$or = [{ name: { $regex: filter, $options: "i" } }, { url: { $regex: filter, $options: "i" } }]; - } - - if (typeof filter !== "undefined" && field === "status") { - matchStage.status = filter === "true"; - } - - const pipeline = [{ $match: matchStage }, { $sort: sort }, { $skip: skip }, ...limitStage]; - - // Add checks - if (limit) { - const checksCollection = "checks"; - - pipeline.push({ - $lookup: { - from: checksCollection, - let: { monitorId: "$_id" }, - pipeline: [ - { - $match: { - $expr: { $eq: ["$monitorId", "$$monitorId"] }, - }, - }, - { $sort: { createdAt: -1 } }, - { $limit: limit }, - ], - as: "checks", - }, - }); - } - - return pipeline; -}; - -const buildGetMonitorsByTeamIdPipeline = (req) => { - let { limit, type, page, rowsPerPage, filter, field, order } = req.query; - - limit = parseInt(limit); - page = parseInt(page); - rowsPerPage = parseInt(rowsPerPage); - if (field === undefined) { - field = "name"; - order = "asc"; - } - // Build the match stage - const matchStage = { teamId: new ObjectId(req.params.teamId) }; - if (type !== undefined) { - matchStage.type = Array.isArray(type) ? { $in: type } : type; - } - - const skip = page && rowsPerPage ? page * rowsPerPage : 0; - const sort = { [field]: order === "asc" ? 1 : -1 }; - return [ - { $match: matchStage }, - { - $facet: { - summary: [ - { - $group: { - _id: null, - totalMonitors: { $sum: 1 }, - upMonitors: { - $sum: { - $cond: [{ $eq: ["$status", true] }, 1, 0], - }, - }, - downMonitors: { - $sum: { - $cond: [{ $eq: ["$status", false] }, 1, 0], - }, - }, - pausedMonitors: { - $sum: { - $cond: [{ $eq: ["$isActive", false] }, 1, 0], - }, - }, - }, - }, - { - $project: { - _id: 0, - }, - }, - ], - monitors: [ - { $sort: sort }, - { - $project: { - _id: 1, - name: 1, - }, - }, - ], - filteredMonitors: [ - ...(filter !== undefined - ? [ - { - $match: { - $or: [{ name: { $regex: filter, $options: "i" } }, { url: { $regex: filter, $options: "i" } }], - }, - }, - ] - : []), - { $sort: sort }, - { $skip: skip }, - ...(rowsPerPage ? [{ $limit: rowsPerPage }] : []), - ...(limit - ? [ - { - $lookup: { - from: "checks", - let: { monitorId: "$_id" }, - pipeline: [ - { - $match: { - $expr: { $eq: ["$monitorId", "$$monitorId"] }, - }, - }, - { $sort: { createdAt: -1 } }, - ...(limit ? [{ $limit: limit }] : []), - ], - as: "standardchecks", - }, - }, - ] - : []), - - { - $addFields: { - checks: { - $switch: { - branches: [ - { - case: { $in: ["$type", ["http", "ping", "docker", "port", "game"]] }, - then: "$standardchecks", - }, - ], - default: [], - }, - }, - }, - }, - { - $project: { - standardchecks: 0, - }, - }, - ], - }, - }, - { - $project: { - summary: { $arrayElemAt: ["$summary", 0] }, - filteredMonitors: 1, - monitors: 1, - }, - }, - ]; -}; - -export { - buildUptimeDetailsPipeline, - buildMonitorStatsPipeline, - buildGetMonitorsByTeamIdPipeline, - buildMonitorSummaryByTeamIdPipeline, - buildMonitorsByTeamIdPipeline, - buildMonitorsAndSummaryByTeamIdPipeline, - buildMonitorsWithChecksByTeamIdPipeline, - buildFilteredMonitorsByTeamIdPipeline, -}; - -export const getAggregateData = async (monitorId, dates) => { - const result = await CheckModel.aggregate([ - { - $match: { - "metadata.monitorId": new ObjectId(monitorId), - "metadata.type": "hardware", - createdAt: { $gte: dates.start, $lte: dates.end }, - }, - }, - { $sort: { createdAt: -1 } }, - { - $group: { - _id: null, - latestCheck: { $first: "$$ROOT" }, - totalChecks: { $sum: 1 }, - }, - }, - ]); - return result[0] || { totalChecks: 0, latestCheck: null }; -}; - -export const getUpChecks = async (monitorId, dates) => { - const count = await CheckModel.countDocuments({ - "metadata.monitorId": new ObjectId(monitorId), - "metadata.type": "hardware", - createdAt: { $gte: dates.start, $lte: dates.end }, - status: true, - }); - return { totalChecks: count }; -}; - -export const getHardwareStats = async (monitorId, dates, dateString) => { - return await CheckModel.aggregate([ - { - $match: { - "metadata.monitorId": new ObjectId(monitorId), - "metadata.type": "hardware", - createdAt: { $gte: dates.start, $lte: dates.end }, - }, - }, - { $sort: { createdAt: 1 } }, - { - $group: { - _id: { $dateToString: { format: dateString, date: "$createdAt" } }, - avgCpuUsage: { $avg: "$cpu.usage_percent" }, - avgMemoryUsage: { $avg: "$memory.usage_percent" }, - avgTemperatures: { $push: { $ifNull: ["$cpu.temperature", [0]] } }, - disks: { $push: "$disk" }, - net: { $push: "$net" }, - updatedAts: { $push: "$updatedAt" }, - sampleDoc: { $first: "$$ROOT" }, - }, - }, - { - $project: { - _id: 1, - avgCpuUsage: 1, - avgMemoryUsage: 1, - avgTemperature: { - $map: { - input: { $range: [0, { $size: { $ifNull: [{ $arrayElemAt: ["$avgTemperatures", 0] }, [0]] } }] }, - as: "idx", - in: { $avg: { $map: { input: "$avgTemperatures", as: "t", in: { $arrayElemAt: ["$$t", "$$idx"] } } } }, - }, - }, - disks: { - $map: { - input: { $range: [0, { $size: { $ifNull: ["$sampleDoc.disk", []] } }] }, - as: "dIdx", - in: { - name: { $concat: ["disk", { $toString: "$$dIdx" }] }, - readSpeed: { $avg: { $map: { input: "$disks", as: "dA", in: { $arrayElemAt: ["$$dA.read_speed_bytes", "$$dIdx"] } } } }, - writeSpeed: { $avg: { $map: { input: "$disks", as: "dA", in: { $arrayElemAt: ["$$dA.write_speed_bytes", "$$dIdx"] } } } }, - totalBytes: { $avg: { $map: { input: "$disks", as: "dA", in: { $arrayElemAt: ["$$dA.total_bytes", "$$dIdx"] } } } }, - freeBytes: { $avg: { $map: { input: "$disks", as: "dA", in: { $arrayElemAt: ["$$dA.free_bytes", "$$dIdx"] } } } }, - usagePercent: { $avg: { $map: { input: "$disks", as: "dA", in: { $arrayElemAt: ["$$dA.usage_percent", "$$dIdx"] } } } }, - }, - }, - }, - net: { - $map: { - input: { $range: [0, { $size: { $ifNull: ["$sampleDoc.net", []] } }] }, - as: "nIdx", - in: { - name: { $arrayElemAt: ["$sampleDoc.net.name", "$$nIdx"] }, - bytesSentPerSecond: { - $let: { - vars: { - tDiff: { $divide: [{ $subtract: [{ $last: "$updatedAts" }, { $first: "$updatedAts" }] }, 1000] }, - f: { $arrayElemAt: [{ $map: { input: { $first: "$net" }, as: "i", in: "$$i.bytes_sent" } }, "$$nIdx"] }, - l: { $arrayElemAt: [{ $map: { input: { $last: "$net" }, as: "i", in: "$$i.bytes_sent" } }, "$$nIdx"] }, - }, - in: { $cond: [{ $gt: ["$$tDiff", 0] }, { $divide: [{ $subtract: ["$$l", "$$f"] }, "$$tDiff"] }, 0] }, - }, - }, - deltaBytesRecv: { - $let: { - vars: { - tDiff: { $divide: [{ $subtract: [{ $last: "$updatedAts" }, { $first: "$updatedAts" }] }, 1000] }, - f: { $arrayElemAt: [{ $map: { input: { $first: "$net" }, as: "i", in: "$$i.bytes_recv" } }, "$$nIdx"] }, - l: { $arrayElemAt: [{ $map: { input: { $last: "$net" }, as: "i", in: "$$i.bytes_recv" } }, "$$nIdx"] }, - }, - in: { $cond: [{ $gt: ["$$tDiff", 0] }, { $divide: [{ $subtract: ["$$l", "$$f"] }, "$$tDiff"] }, 0] }, - }, - }, - deltaPacketsSent: { - $let: { - vars: { - tDiff: { $divide: [{ $subtract: [{ $last: "$updatedAts" }, { $first: "$updatedAts" }] }, 1000] }, - f: { $arrayElemAt: [{ $map: { input: { $first: "$net" }, as: "i", in: "$$i.packets_sent" } }, "$$nIdx"] }, - l: { $arrayElemAt: [{ $map: { input: { $last: "$net" }, as: "i", in: "$$i.packets_sent" } }, "$$nIdx"] }, - }, - in: { $cond: [{ $gt: ["$$tDiff", 0] }, { $divide: [{ $subtract: ["$$l", "$$f"] }, "$$tDiff"] }, 0] }, - }, - }, - deltaPacketsRecv: { - $let: { - vars: { - tDiff: { $divide: [{ $subtract: [{ $last: "$updatedAts" }, { $first: "$updatedAts" }] }, 1000] }, - f: { $arrayElemAt: [{ $map: { input: { $first: "$net" }, as: "i", in: "$$i.packets_recv" } }, "$$nIdx"] }, - l: { $arrayElemAt: [{ $map: { input: { $last: "$net" }, as: "i", in: "$$i.packets_recv" } }, "$$nIdx"] }, - }, - in: { $cond: [{ $gt: ["$$tDiff", 0] }, { $divide: [{ $subtract: ["$$l", "$$f"] }, "$$tDiff"] }, 0] }, - }, - }, - deltaErrIn: { - $let: { - vars: { - tDiff: { $divide: [{ $subtract: [{ $last: "$updatedAts" }, { $first: "$updatedAts" }] }, 1000] }, - f: { $arrayElemAt: [{ $map: { input: { $first: "$net" }, as: "i", in: "$$i.err_in" } }, "$$nIdx"] }, - l: { $arrayElemAt: [{ $map: { input: { $last: "$net" }, as: "i", in: "$$i.err_in" } }, "$$nIdx"] }, - }, - in: { $cond: [{ $gt: ["$$tDiff", 0] }, { $divide: [{ $subtract: ["$$l", "$$f"] }, "$$tDiff"] }, 0] }, - }, - }, - deltaErrOut: { - $let: { - vars: { - tDiff: { $divide: [{ $subtract: [{ $last: "$updatedAts" }, { $first: "$updatedAts" }] }, 1000] }, - f: { $arrayElemAt: [{ $map: { input: { $first: "$net" }, as: "i", in: "$$i.err_out" } }, "$$nIdx"] }, - l: { $arrayElemAt: [{ $map: { input: { $last: "$net" }, as: "i", in: "$$i.err_out" } }, "$$nIdx"] }, - }, - in: { $cond: [{ $gt: ["$$tDiff", 0] }, { $divide: [{ $subtract: ["$$l", "$$f"] }, "$$tDiff"] }, 0] }, - }, - }, - deltaDropIn: { - $let: { - vars: { - tDiff: { $divide: [{ $subtract: [{ $last: "$updatedAts" }, { $first: "$updatedAts" }] }, 1000] }, - f: { $arrayElemAt: [{ $map: { input: { $first: "$net" }, as: "i", in: "$$i.drop_in" } }, "$$nIdx"] }, - l: { $arrayElemAt: [{ $map: { input: { $last: "$net" }, as: "i", in: "$$i.drop_in" } }, "$$nIdx"] }, - }, - in: { $cond: [{ $gt: ["$$tDiff", 0] }, { $divide: [{ $subtract: ["$$l", "$$f"] }, "$$tDiff"] }, 0] }, - }, - }, - deltaDropOut: { - $let: { - vars: { - tDiff: { $divide: [{ $subtract: [{ $last: "$updatedAts" }, { $first: "$updatedAts" }] }, 1000] }, - f: { $arrayElemAt: [{ $map: { input: { $first: "$net" }, as: "i", in: "$$i.drop_out" } }, "$$nIdx"] }, - l: { $arrayElemAt: [{ $map: { input: { $last: "$net" }, as: "i", in: "$$i.drop_out" } }, "$$nIdx"] }, - }, - in: { $cond: [{ $gt: ["$$tDiff", 0] }, { $divide: [{ $subtract: ["$$l", "$$f"] }, "$$tDiff"] }, 0] }, - }, - }, - }, - }, - }, - }, - }, - { $sort: { _id: 1 } }, - ]); -}; diff --git a/server/src/db/modules/notificationModule.js b/server/src/db/modules/notificationModule.js index 3c6edb54a..f45900184 100755 --- a/server/src/db/modules/notificationModule.js +++ b/server/src/db/modules/notificationModule.js @@ -1,5 +1,3 @@ -// import Notification from "../../models/Notification.js"; -// import Monitor from "../../models/Monitor.js"; const SERVICE_NAME = "notificationModule"; class NotificationModule { diff --git a/server/src/db/modules/statusPageModule.js b/server/src/db/modules/statusPageModule.js index 999e0bdc9..152f9efc5 100755 --- a/server/src/db/modules/statusPageModule.js +++ b/server/src/db/modules/statusPageModule.js @@ -1,4 +1,3 @@ -// import StatusPage from "../../models/StatusPage.js"; // import { NormalizeData } from "../../../utils/dataUtils.js"; // import ServiceRegistry from "../../../service/system/serviceRegistry.js"; // import StringService from "../../../service/system/stringService.js"; @@ -6,10 +5,11 @@ const SERVICE_NAME = "statusPageModule"; class StatusPageModule { - constructor({ StatusPage, NormalizeData, stringService }) { + constructor({ StatusPage, NormalizeData, stringService, AppSettings }) { this.StatusPage = StatusPage; this.NormalizeData = NormalizeData; this.stringService = stringService; + this.AppSettings = AppSettings; } createStatusPage = async ({ statusPageData, image, userId, teamId }) => { @@ -260,11 +260,16 @@ class StatusPageModule { const { statusPage, monitors } = statusPageQuery[0]; + const appSettings = await this.AppSettings.findOne({ singleton: true }).lean(); + const showURL = appSettings?.showURL === true; + const normalizedMonitors = monitors.map((monitor) => { - return { - ...monitor, - checks: this.NormalizeData(monitor.checks, 10, 100), - }; + const normalizedChecks = this.NormalizeData(monitor.checks, 10, 100); + if (!showURL) { + const { url, port, secret, notifications, ...rest } = monitor; + return { ...rest, checks: normalizedChecks }; + } + return { ...monitor, checks: normalizedChecks }; }); return { statusPage, monitors: normalizedMonitors }; @@ -287,6 +292,7 @@ class StatusPageModule { deleteStatusPagesByMonitorId = async (monitorId) => { try { await this.StatusPage.deleteMany({ monitors: { $in: [monitorId] } }); + await this.StatusPage.deleteMany({ subMonitors: { $in: [monitorId] } }); } catch (error) { error.service = SERVICE_NAME; error.method = "deleteStatusPageByMonitorId"; diff --git a/server/src/middleware/v1/verifyJWT.js b/server/src/middleware/v1/verifyJWT.ts similarity index 74% rename from server/src/middleware/v1/verifyJWT.js rename to server/src/middleware/v1/verifyJWT.ts index cf983a6c8..b3211d7b6 100755 --- a/server/src/middleware/v1/verifyJWT.js +++ b/server/src/middleware/v1/verifyJWT.ts @@ -1,3 +1,5 @@ +import { NextFunction, Request, Response } from "express"; + import jwt from "jsonwebtoken"; import ServiceRegistry from "../../service/system/serviceRegistry.js"; import SettingsService from "../../service/system/settingsService.js"; @@ -5,20 +7,12 @@ import StringService from "../../service/system/stringService.js"; const SERVICE_NAME = "verifyJWT"; const TOKEN_PREFIX = "Bearer "; -/** - * Verifies the JWT token - * @function - * @param {express.Request} req - * @param {express.Response} res - * @param {express.NextFunction} next - * @returns {express.Response} - */ -const verifyJWT = (req, res, next) => { +const verifyJWT = (req: Request, res: Response, next: NextFunction) => { const stringService = ServiceRegistry.get(StringService.SERVICE_NAME); const token = req.headers["authorization"]; // Make sure a token is provided if (!token) { - const error = new Error(stringService.noAuthToken); + const error: any = new Error(stringService.noAuthToken); error.status = 401; error.service = SERVICE_NAME; next(error); @@ -26,7 +20,7 @@ const verifyJWT = (req, res, next) => { } // Make sure it is properly formatted if (!token.startsWith(TOKEN_PREFIX)) { - const error = new Error(stringService.invalidAuthToken); // Instantiate a new Error object for improperly formatted token + const error: any = new Error(stringService.invalidAuthToken); // Instantiate a new Error object for improperly formatted token error.status = 401; error.service = SERVICE_NAME; error.method = "verifyJWT"; @@ -37,7 +31,7 @@ const verifyJWT = (req, res, next) => { const parsedToken = token.slice(TOKEN_PREFIX.length, token.length); // Verify the token's authenticity const { jwtSecret } = ServiceRegistry.get(SettingsService.SERVICE_NAME).getSettings(); - jwt.verify(parsedToken, jwtSecret, (err, decoded) => { + jwt.verify(parsedToken, jwtSecret, (err: any, decoded: any) => { if (err) { const errorMessage = err.name === "TokenExpiredError" ? stringService.expiredAuthToken : stringService.invalidAuthToken; err.details = { msg: errorMessage }; diff --git a/server/src/repositories/checks/IChecksRepository.ts b/server/src/repositories/checks/IChecksRepository.ts index cedea8d86..ab5dc6ce5 100644 --- a/server/src/repositories/checks/IChecksRepository.ts +++ b/server/src/repositories/checks/IChecksRepository.ts @@ -1,65 +1,41 @@ -import type { Check, CheckAudits, MonitorType } from "@/types/index.js"; +import type { + Check, + ChecksQueryResult, + ChecksSummary, + MonitorType, + PageSpeedChecksResult, + HardwareChecksResult, + UptimeChecksResult, +} from "@/types/index.js"; import type { LatestChecksMap } from "@/repositories/checks/MongoChecksRepistory.js"; -export interface PageSpeedChecksResult { - monitorType: "pagespeed"; - checks: Check[]; -} - -export interface HardwareChecksResult { - monitorType: "hardware"; - aggregateData: { - latestCheck: Check | null; - totalChecks: number; - }; - upChecks: { - totalChecks: number; - }; - checks: Array<{ - _id: string; - avgCpuUsage: number; - avgMemoryUsage: number; - avgTemperature: number[]; - disks: Array<{ - name: string; - readSpeed: number; - writeSpeed: number; - totalBytes: number; - freeBytes: number; - usagePercent: number; - }>; - net: Array<{ - name: string; - bytesSentPerSecond: number; - deltaBytesRecv: number; - deltaPacketsSent: number; - deltaPacketsRecv: number; - deltaErrIn: number; - deltaErrOut: number; - deltaDropIn: number; - deltaDropOut: number; - deltaFifoIn: number; - deltaFifoOut: number; - }>; - }>; -} - -export interface UptimeChecksResult { - monitorType: Exclude; - groupedChecks: Array<{ _id: string; avgResponseTime: number; totalChecks: number }>; - groupedUpChecks: Array<{ _id: string; totalChecks: number; avgResponseTime: number }>; - groupedDownChecks: Array<{ _id: string; totalChecks: number; avgResponseTime: number }>; - uptimePercentage: number; - avgResponseTime: number; -} - export interface IChecksRepository { - findLatestChecksByMonitorIds(monitorIds: string[], options?: { limitPerMonitor?: number }): Promise; - findDateRangeChecksByMonitor( + // create + createChecks(checks: Check[]): Promise; + + // single fetch + // collection fetch + findByMonitorId( + monitorId: string, + sortOrder: string, + dateRange: string, + filter: string, + page: number, + rowsPerPage: number, + status: boolean | undefined + ): Promise; + findByTeamId(sortOrder: string, dateRange: string, filter: string, page: number, rowsPerPage: number, teamId: string): Promise; + findLatestByMonitorIds(monitorIds: string[], options?: { limitPerMonitor?: number }): Promise; + findByDateRangeAndMonitorId( monitorId: string, startDate: Date, endDate: Date, dateString: string, options?: { type?: MonitorType } ): Promise; + findSummaryByTeamId(teamId: string): Promise; + // update + //delete + deleteByMonitorId(monitorId: string): Promise; + deleteByTeamId(teamId: string): Promise; } diff --git a/server/src/repositories/checks/MongoChecksRepistory.ts b/server/src/repositories/checks/MongoChecksRepistory.ts index 7ede5587e..b9cf2041f 100644 --- a/server/src/repositories/checks/MongoChecksRepistory.ts +++ b/server/src/repositories/checks/MongoChecksRepistory.ts @@ -10,20 +10,36 @@ import type { CheckMemoryInfo, CheckMetadata, CheckNetworkInterfaceInfo, - CheckTimings, + GotTimings, MonitorType, } from "@/types/index.js"; import { CheckModel, type CheckDocument } from "@/db/models/index.js"; import mongoose from "mongoose"; -import { - getAggregateData as getHardwareAggregateData, - getHardwareStats, - getUpChecks as getHardwareUpChecks, -} from "@/db/modules/monitorModuleQueries.js"; + +const SERVICE_NAME = "StatusService"; + +const dateRangeLookup: Record = { + recent: new Date(new Date().setDate(new Date().getDate() - 2)), + hour: new Date(new Date().setHours(new Date().getHours() - 1)), + day: new Date(new Date().setDate(new Date().getDate() - 1)), + week: new Date(new Date().setDate(new Date().getDate() - 7)), + month: new Date(new Date().setMonth(new Date().getMonth() - 1)), + all: undefined, +}; export type LatestChecksMap = Record; +type DateRange = { start: Date; end: Date }; +type HardwareAggregateData = { latestCheck: CheckDocument | null; totalChecks: number }; +type HardwareUpChecks = { totalChecks: number }; + +class MongoChecksRepository implements IChecksRepository { + static SERVICE_NAME = SERVICE_NAME; + + private logger: any; + constructor(logger: any) { + this.logger = logger; + } -class MongoChecksRepistory implements IChecksRepository { private toEntity = (doc: CheckDocument): Check => { const toStringId = (value: mongoose.Types.ObjectId | string | undefined | null): string => { if (!value) { @@ -46,7 +62,7 @@ class MongoChecksRepistory implements IChecksRepository { return toDateString(value); }; - const mapTimings = (timings?: CheckTimings): CheckTimings => { + const mapTimings = (timings?: GotTimings): GotTimings => { const phases = timings?.phases ?? { wait: 0, dns: 0, @@ -135,11 +151,11 @@ class MongoChecksRepistory implements IChecksRepository { return undefined; } return { - cls: audits.cls ?? 0, - si: audits.si ?? 0, - fcp: audits.fcp ?? 0, - lcp: audits.lcp ?? 0, - tbt: audits.tbt ?? 0, + cls: audits.cls, + si: audits.si, + fcp: audits.fcp, + lcp: audits.lcp, + tbt: audits.tbt, }; }; @@ -178,24 +194,154 @@ class MongoChecksRepistory implements IChecksRepository { }; }; - findLatestChecksByMonitorIds = async (monitorIds: string[], options?: { limitPerMonitor?: number }): Promise => { + createChecks = async (checks: Check[]) => { + return await CheckModel.insertMany(checks); + }; + + findByMonitorId = async ( + monitorId: string, + sortOrder: string, + dateRange: string, + filter: string, + page: number, + rowsPerPage: number, + status: boolean | undefined + ) => { + // Match + const matchStage: Record = { + "metadata.monitorId": new mongoose.Types.ObjectId(monitorId), + ...(typeof status !== "undefined" && { status }), + ...(dateRangeLookup[dateRange] && { + createdAt: { + $gte: dateRangeLookup[dateRange], + }, + }), + }; + + if (filter !== undefined) { + switch (filter) { + case "all": + break; + case "down": + break; + case "resolve": + matchStage.statusCode = 5000; + break; + default: + this.logger.warn({ + message: "invalid filter", + service: SERVICE_NAME, + method: "getChecks", + }); + break; + } + } + + //Sort + const convertedSortOrder = sortOrder === "asc" ? 1 : -1; + + // Pagination + let skip = 0; + if (page && rowsPerPage) { + skip = page * rowsPerPage; + } + + const checks = await CheckModel.aggregate([ + { $match: matchStage }, + { $sort: { createdAt: convertedSortOrder } }, + { + $facet: { + summary: [{ $count: "checksCount" }], + checks: [{ $skip: skip }, { $limit: rowsPerPage }], + }, + }, + { + $project: { + checksCount: { + $ifNull: [{ $arrayElemAt: ["$summary.checksCount", 0] }, 0], + }, + checks: { + $ifNull: ["$checks", []], + }, + }, + }, + ]); + return checks[0]; + }; + + findByTeamId = async (sortOrder: string, dateRange: string, filter: string, page: number, rowsPerPage: number, teamId: string) => { + const matchStage: Record = { + "metadata.teamId": new mongoose.Types.ObjectId(teamId), + status: false, + ...(dateRangeLookup[dateRange] && { + createdAt: { + $gte: dateRangeLookup[dateRange], + }, + }), + }; + // Add filter to match stage + if (filter !== undefined) { + switch (filter) { + case "all": + break; + case "down": + break; + case "resolve": + matchStage.statusCode = 5000; + break; + default: + this.logger.warn({ + message: "invalid filter", + service: SERVICE_NAME, + method: "getChecksByTeam", + }); + break; + } + } + + const parsedSortOrder = sortOrder === "asc" ? 1 : -1; + + // pagination + let skip = 0; + if (page && rowsPerPage) { + skip = page * rowsPerPage; + } + + const aggregatePipeline: any = [ + { $match: matchStage }, + + { $sort: { createdAt: parsedSortOrder } }, + { + $facet: { + summary: [{ $count: "checksCount" }], + checks: [{ $skip: skip }, { $limit: rowsPerPage }], + }, + }, + { + $project: { + checksCount: { $arrayElemAt: ["$summary.checksCount", 0] }, + checks: "$checks", + }, + }, + ]; + + const checks = await CheckModel.aggregate(aggregatePipeline); + return checks[0]; + }; + + findLatestByMonitorIds = async (monitorIds: string[], options?: { limitPerMonitor?: number }): Promise => { if (monitorIds.length === 0) { return {}; } const mongoIds = monitorIds.map((id) => new mongoose.Types.ObjectId(id)); const limitPerMonitor = options?.limitPerMonitor ?? 25; - const maxIntervalMs = Number(10 * 60 * 1000); - const bufferMs = Number(maxIntervalMs); - const lookbackMs = limitPerMonitor * maxIntervalMs + bufferMs; - - const cutoffDate = new Date(Date.now() - lookbackMs); const checkGroups = await CheckModel.aggregate([ { $match: { "metadata.monitorId": { $in: mongoIds }, - createdAt: { $gte: cutoffDate }, }, }, + { $sort: { "metadata.monitorId": 1, createdAt: -1 } }, { $group: { _id: "$metadata.monitorId", @@ -217,7 +363,7 @@ class MongoChecksRepistory implements IChecksRepository { }, {}); }; - findDateRangeChecksByMonitor = async (monitorId: string, startDate: Date, endDate: Date, dateString: string, options?: { type?: MonitorType }) => { + findByDateRangeAndMonitorId = async (monitorId: string, startDate: Date, endDate: Date, dateString: string, options?: { type?: MonitorType }) => { const monitorObjectId = new mongoose.Types.ObjectId(monitorId); if (options?.type === "hardware") { return this.findHardwareDateRangeChecks(monitorObjectId, startDate, endDate, dateString); @@ -228,6 +374,63 @@ class MongoChecksRepistory implements IChecksRepository { return this.findUptimeDateRangeChecks(options?.type ?? "http", monitorObjectId, startDate, endDate, dateString); }; + findSummaryByTeamId = async (teamId: string) => { + const matchStage = { + "metadata.teamId": new mongoose.Types.ObjectId(teamId), + }; + const checks = await CheckModel.aggregate([ + { $match: matchStage }, + { + $facet: { + summary: [ + { + $group: { + _id: null, + totalChecks: { $sum: { $cond: [{ $eq: ["$status", false] }, 1, 0] } }, + resolvedChecks: { + $sum: { + $cond: [{ $and: [{ $eq: ["$ack", true] }, { $eq: ["$status", false] }] }, 1, 0], + }, + }, + downChecks: { + $sum: { + $cond: [{ $and: [{ $eq: ["$ack", false] }, { $eq: ["$status", false] }] }, 1, 0], + }, + }, + cannotResolveChecks: { + $sum: { + $cond: [{ $eq: ["$statusCode", 5000] }, 1, 0], + }, + }, + }, + }, + { + $project: { + _id: 0, + }, + }, + ], + }, + }, + { + $project: { + summary: { $arrayElemAt: ["$summary", 0] }, + }, + }, + ]); + return checks[0].summary; + }; + + deleteByMonitorId = async (monitorId: string): Promise => { + const result = await CheckModel.deleteMany({ "metadata.monitorId": new mongoose.Types.ObjectId(monitorId) }); + return result.deletedCount; + }; + + deleteByTeamId = async (teamId: string) => { + const deleteResult = await CheckModel.deleteMany({ "metadata.teamId": teamId }); + return deleteResult.deletedCount; + }; + private findUptimeDateRangeChecks = async ( monitorType: Exclude, monitorObjectId: mongoose.Types.ObjectId, @@ -328,9 +531,9 @@ class MongoChecksRepistory implements IChecksRepository { const monitorId = monitorObjectId.toHexString(); const dates = { start: startDate, end: endDate }; const [aggregateDataDoc, upChecksDoc, hardwareMetrics] = await Promise.all([ - getHardwareAggregateData(monitorId, dates), - getHardwareUpChecks(monitorId, dates), - getHardwareStats(monitorId, dates, dateString), + this.getHardwareAggregateData(monitorId, dates), + this.getHardwareUpChecks(monitorId, dates), + this.getHardwareStats(monitorId, dates, dateString), ]); const aggregateData = { @@ -390,6 +593,180 @@ class MongoChecksRepistory implements IChecksRepository { checks: checks.map((doc) => this.toEntity(doc)), }; }; + + private getHardwareAggregateData = async (monitorId: string, dates: DateRange): Promise => { + const result = await CheckModel.aggregate([ + { + $match: { + "metadata.monitorId": new mongoose.Types.ObjectId(monitorId), + "metadata.type": "hardware", + createdAt: { $gte: dates.start, $lte: dates.end }, + }, + }, + { $sort: { createdAt: -1 } }, + { + $group: { + _id: null, + latestCheck: { $first: "$$ROOT" }, + totalChecks: { $sum: 1 }, + }, + }, + ]); + return result[0] || { totalChecks: 0, latestCheck: null }; + }; + + private getHardwareUpChecks = async (monitorId: string, dates: DateRange): Promise => { + const count = await CheckModel.countDocuments({ + "metadata.monitorId": new mongoose.Types.ObjectId(monitorId), + "metadata.type": "hardware", + createdAt: { $gte: dates.start, $lte: dates.end }, + status: true, + }); + return { totalChecks: count }; + }; + + private getHardwareStats = async (monitorId: string, dates: DateRange, dateString: string) => { + return await CheckModel.aggregate([ + { + $match: { + "metadata.monitorId": new mongoose.Types.ObjectId(monitorId), + "metadata.type": "hardware", + createdAt: { $gte: dates.start, $lte: dates.end }, + }, + }, + { $sort: { createdAt: 1 } }, + { + $group: { + _id: { $dateToString: { format: dateString, date: "$createdAt" } }, + avgCpuUsage: { $avg: "$cpu.usage_percent" }, + avgMemoryUsage: { $avg: "$memory.usage_percent" }, + avgTemperatures: { $push: { $ifNull: ["$cpu.temperature", [0]] } }, + disks: { $push: "$disk" }, + net: { $push: "$net" }, + updatedAts: { $push: "$updatedAt" }, + sampleDoc: { $first: "$$ROOT" }, + }, + }, + { + $project: { + _id: 1, + avgCpuUsage: 1, + avgMemoryUsage: 1, + avgTemperature: { + $map: { + input: { $range: [0, { $size: { $ifNull: [{ $arrayElemAt: ["$avgTemperatures", 0] }, [0]] } }] }, + as: "idx", + in: { $avg: { $map: { input: "$avgTemperatures", as: "t", in: { $arrayElemAt: ["$$t", "$$idx"] } } } }, + }, + }, + disks: { + $map: { + input: { $range: [0, { $size: { $ifNull: ["$sampleDoc.disk", []] } }] }, + as: "dIdx", + in: { + name: { $concat: ["disk", { $toString: "$$dIdx" }] }, + readSpeed: { $avg: { $map: { input: "$disks", as: "dA", in: { $arrayElemAt: ["$$dA.read_speed_bytes", "$$dIdx"] } } } }, + writeSpeed: { $avg: { $map: { input: "$disks", as: "dA", in: { $arrayElemAt: ["$$dA.write_speed_bytes", "$$dIdx"] } } } }, + totalBytes: { $avg: { $map: { input: "$disks", as: "dA", in: { $arrayElemAt: ["$$dA.total_bytes", "$$dIdx"] } } } }, + freeBytes: { $avg: { $map: { input: "$disks", as: "dA", in: { $arrayElemAt: ["$$dA.free_bytes", "$$dIdx"] } } } }, + usagePercent: { $avg: { $map: { input: "$disks", as: "dA", in: { $arrayElemAt: ["$$dA.usage_percent", "$$dIdx"] } } } }, + }, + }, + }, + net: { + $map: { + input: { $range: [0, { $size: { $ifNull: ["$sampleDoc.net", []] } }] }, + as: "nIdx", + in: { + name: { $arrayElemAt: ["$sampleDoc.net.name", "$$nIdx"] }, + bytesSentPerSecond: { + $let: { + vars: { + tDiff: { $divide: [{ $subtract: [{ $last: "$updatedAts" }, { $first: "$updatedAts" }] }, 1000] }, + f: { $arrayElemAt: [{ $map: { input: { $first: "$net" }, as: "i", in: "$$i.bytes_sent" } }, "$$nIdx"] }, + l: { $arrayElemAt: [{ $map: { input: { $last: "$net" }, as: "i", in: "$$i.bytes_sent" } }, "$$nIdx"] }, + }, + in: { $cond: [{ $gt: ["$$tDiff", 0] }, { $divide: [{ $subtract: ["$$l", "$$f"] }, "$$tDiff"] }, 0] }, + }, + }, + deltaBytesRecv: { + $let: { + vars: { + tDiff: { $divide: [{ $subtract: [{ $last: "$updatedAts" }, { $first: "$updatedAts" }] }, 1000] }, + f: { $arrayElemAt: [{ $map: { input: { $first: "$net" }, as: "i", in: "$$i.bytes_recv" } }, "$$nIdx"] }, + l: { $arrayElemAt: [{ $map: { input: { $last: "$net" }, as: "i", in: "$$i.bytes_recv" } }, "$$nIdx"] }, + }, + in: { $cond: [{ $gt: ["$$tDiff", 0] }, { $divide: [{ $subtract: ["$$l", "$$f"] }, "$$tDiff"] }, 0] }, + }, + }, + deltaPacketsSent: { + $let: { + vars: { + tDiff: { $divide: [{ $subtract: [{ $last: "$updatedAts" }, { $first: "$updatedAts" }] }, 1000] }, + f: { $arrayElemAt: [{ $map: { input: { $first: "$net" }, as: "i", in: "$$i.packets_sent" } }, "$$nIdx"] }, + l: { $arrayElemAt: [{ $map: { input: { $last: "$net" }, as: "i", in: "$$i.packets_sent" } }, "$$nIdx"] }, + }, + in: { $cond: [{ $gt: ["$$tDiff", 0] }, { $divide: [{ $subtract: ["$$l", "$$f"] }, "$$tDiff"] }, 0] }, + }, + }, + deltaPacketsRecv: { + $let: { + vars: { + tDiff: { $divide: [{ $subtract: [{ $last: "$updatedAts" }, { $first: "$updatedAts" }] }, 1000] }, + f: { $arrayElemAt: [{ $map: { input: { $first: "$net" }, as: "i", in: "$$i.packets_recv" } }, "$$nIdx"] }, + l: { $arrayElemAt: [{ $map: { input: { $last: "$net" }, as: "i", in: "$$i.packets_recv" } }, "$$nIdx"] }, + }, + in: { $cond: [{ $gt: ["$$tDiff", 0] }, { $divide: [{ $subtract: ["$$l", "$$f"] }, "$$tDiff"] }, 0] }, + }, + }, + deltaErrIn: { + $let: { + vars: { + tDiff: { $divide: [{ $subtract: [{ $last: "$updatedAts" }, { $first: "$updatedAts" }] }, 1000] }, + f: { $arrayElemAt: [{ $map: { input: { $first: "$net" }, as: "i", in: "$$i.err_in" } }, "$$nIdx"] }, + l: { $arrayElemAt: [{ $map: { input: { $last: "$net" }, as: "i", in: "$$i.err_in" } }, "$$nIdx"] }, + }, + in: { $cond: [{ $gt: ["$$tDiff", 0] }, { $divide: [{ $subtract: ["$$l", "$$f"] }, "$$tDiff"] }, 0] }, + }, + }, + deltaErrOut: { + $let: { + vars: { + tDiff: { $divide: [{ $subtract: [{ $last: "$updatedAts" }, { $first: "$updatedAts" }] }, 1000] }, + f: { $arrayElemAt: [{ $map: { input: { $first: "$net" }, as: "i", in: "$$i.err_out" } }, "$$nIdx"] }, + l: { $arrayElemAt: [{ $map: { input: { $last: "$net" }, as: "i", in: "$$i.err_out" } }, "$$nIdx"] }, + }, + in: { $cond: [{ $gt: ["$$tDiff", 0] }, { $divide: [{ $subtract: ["$$l", "$$f"] }, "$$tDiff"] }, 0] }, + }, + }, + deltaDropIn: { + $let: { + vars: { + tDiff: { $divide: [{ $subtract: [{ $last: "$updatedAts" }, { $first: "$updatedAts" }] }, 1000] }, + f: { $arrayElemAt: [{ $map: { input: { $first: "$net" }, as: "i", in: "$$i.drop_in" } }, "$$nIdx"] }, + l: { $arrayElemAt: [{ $map: { input: { $last: "$net" }, as: "i", in: "$$i.drop_in" } }, "$$nIdx"] }, + }, + in: { $cond: [{ $gt: ["$$tDiff", 0] }, { $divide: [{ $subtract: ["$$l", "$$f"] }, "$$tDiff"] }, 0] }, + }, + }, + deltaDropOut: { + $let: { + vars: { + tDiff: { $divide: [{ $subtract: [{ $last: "$updatedAts" }, { $first: "$updatedAts" }] }, 1000] }, + f: { $arrayElemAt: [{ $map: { input: { $first: "$net" }, as: "i", in: "$$i.drop_out" } }, "$$nIdx"] }, + l: { $arrayElemAt: [{ $map: { input: { $last: "$net" }, as: "i", in: "$$i.drop_out" } }, "$$nIdx"] }, + }, + in: { $cond: [{ $gt: ["$$tDiff", 0] }, { $divide: [{ $subtract: ["$$l", "$$f"] }, "$$tDiff"] }, 0] }, + }, + }, + }, + }, + }, + }, + }, + { $sort: { _id: 1 } }, + ]); + }; } -export default MongoChecksRepistory; +export default MongoChecksRepository; diff --git a/server/src/repositories/incidents/IIncidentsRepository.ts b/server/src/repositories/incidents/IIncidentsRepository.ts new file mode 100644 index 000000000..7c2b0179e --- /dev/null +++ b/server/src/repositories/incidents/IIncidentsRepository.ts @@ -0,0 +1,26 @@ +import type { Incident } from "@/types/index.js"; +import type { IncidentSummary } from "@/types/index.js"; +export interface IIncidentsRepository { + // create + create(incident: Partial): Promise; + // fetch + findActiveByIncidentId(incidentId: string, teamId: string): Promise; + findActiveByMonitorId(monitorId: string, teamId: string): Promise; + findByTeamId( + teamId: string, + startDate: Date | undefined, + page: number, + rowsPerPage: number, + sortOrder?: string, + status?: boolean, + monitorId?: string, + resolutionType?: string + ): Promise; + findSummaryByTeamId(teamId: string, limit?: number): Promise; + countByTeamId(teamId: string, startDate: Date | undefined, status?: boolean, monitorId?: string, resolutionType?: string): Promise; + + // update + updateById(incidentId: string, teamId: string, updateData: Partial): Promise; + // delete + // other +} diff --git a/server/src/repositories/incidents/MongoIncidentRepository.ts b/server/src/repositories/incidents/MongoIncidentRepository.ts new file mode 100644 index 000000000..10cb47213 --- /dev/null +++ b/server/src/repositories/incidents/MongoIncidentRepository.ts @@ -0,0 +1,265 @@ +import { IncidentModel } from "@/db/models/index.js"; +import type { IncidentDocument } from "@/db/models/Incident.js"; +import type { Incident, IncidentSummary } from "@/types/index.js"; +import type { IIncidentsRepository } from "@/repositories/index.js"; +import mongoose from "mongoose"; +import { AppError } from "@/utils/AppError.js"; + +class MongoIncidentRepository implements IIncidentsRepository { + private toStringId = (value?: mongoose.Types.ObjectId | string | null): string => { + if (!value) { + return ""; + } + return value instanceof mongoose.Types.ObjectId ? value.toString() : String(value); + }; + + private toDateString = (value?: Date | string | null): string => { + if (!value) { + return new Date(0).toISOString(); + } + return value instanceof Date ? value.toISOString() : new Date(value).toISOString(); + }; + + private buildMatchStage({ + teamId, + startDate, + status, + monitorId, + resolutionType, + }: { + teamId: string; + startDate: Date | undefined; + status?: boolean; + monitorId?: string; + resolutionType?: string; + }): Record { + const matchStage: Record = { + teamId: new mongoose.Types.ObjectId(teamId), + ...(status !== undefined && { status }), + ...(monitorId && { monitorId: new mongoose.Types.ObjectId(monitorId) }), + ...(resolutionType && { resolutionType }), + }; + + if (startDate) { + matchStage.createdAt = { $gte: startDate }; + } + return matchStage; + } + + protected toEntity = (doc: IncidentDocument): Incident => { + return { + id: this.toStringId(doc._id), + monitorId: this.toStringId(doc.monitorId), + teamId: this.toStringId(doc.teamId), + startTime: this.toDateString(doc.startTime), + endTime: doc.endTime ? this.toDateString(doc.endTime) : null, + status: doc.status, + message: doc.message ?? null, + statusCode: doc.statusCode ?? null, + resolutionType: doc.resolutionType ?? null, + resolvedBy: doc.resolvedBy ? this.toStringId(doc.resolvedBy) : null, + comment: doc.comment ?? null, + createdAt: this.toDateString(doc.createdAt), + updatedAt: this.toDateString(doc.updatedAt), + }; + }; + + protected mapDocuments = (documents: IncidentDocument[] | IncidentDocument | null): Incident[] => { + if (!documents) { + return []; + } + if (Array.isArray(documents)) { + return documents.map((doc) => this.toEntity(doc)); + } + return [this.toEntity(documents)]; + }; + + async create(incident: Partial): Promise { + const newIncident = await IncidentModel.create(incident); + return this.toEntity(newIncident); + } + + findActiveByIncidentId = async (incidentId: string, teamId: string): Promise => { + const incident = await IncidentModel.findOne({ + _id: new mongoose.Types.ObjectId(incidentId), + teamId: new mongoose.Types.ObjectId(teamId), + status: true, + }); + if (!incident) { + return null; + } + return this.toEntity(incident); + }; + + findActiveByMonitorId = async (monitorId: string, teamId: string): Promise => { + const incident = await IncidentModel.findOne({ + monitorId: new mongoose.Types.ObjectId(monitorId), + teamId: new mongoose.Types.ObjectId(teamId), + status: true, + }); + if (!incident) { + return null; + } + return this.toEntity(incident); + }; + + findByTeamId = async ( + teamId: string, + startDate: Date | undefined, + page: number, + rowsPerPage: number, + sortOrder?: string, + status?: boolean, + monitorId?: string, + resolutionType?: string + ): Promise => { + const matchStage = this.buildMatchStage({ teamId, startDate, status, monitorId, resolutionType }); + const incidents = await IncidentModel.find(matchStage) + .sort({ createdAt: sortOrder === "asc" ? 1 : -1 }) + .skip(page * rowsPerPage) + .limit(rowsPerPage); + return this.mapDocuments(incidents); + }; + + updateById = async (incidentId: string, teamId: string, patch: Partial) => { + const updatedIncident = await IncidentModel.findOneAndUpdate( + { _id: new mongoose.Types.ObjectId(incidentId), teamId: new mongoose.Types.ObjectId(teamId) }, + { + $set: { + ...patch, + }, + }, + { new: true, runValidators: true } + ); + if (!updatedIncident) { + throw new AppError({ message: `Failed to update incident with id ${incidentId}`, status: 500 }); + } + return this.toEntity(updatedIncident); + }; + + countByTeamId = async ( + teamId: string, + startDate: Date | undefined, + status?: boolean, + monitorId?: string, + resolutionType?: string + ): Promise => { + const matchStage = this.buildMatchStage({ teamId, startDate, status, monitorId, resolutionType }); + return IncidentModel.countDocuments(matchStage); + }; + + findSummaryByTeamId = async (teamId: string, limit: number): Promise => { + const matchStage = { teamId: new mongoose.Types.ObjectId(teamId) }; + + const counts = await IncidentModel.aggregate([ + { $match: matchStage }, + { + $group: { + _id: "$status", + count: { $sum: 1 }, + manualResolutions: { + $sum: { $cond: [{ $eq: ["$resolutionType", "manual"] }, 1, 0] }, + }, + automaticResolutions: { + $sum: { $cond: [{ $eq: ["$resolutionType", "automatic"] }, 1, 0] }, + }, + }, + }, + ]); + + let total = 0; + let active = 0; + let manual = 0; + let automatic = 0; + + counts.forEach((item) => { + total += item.count; + if (item._id === true) { + active = item.count; + } + manual += item.manualResolutions; + automatic += item.automaticResolutions; + }); + + const resolutionTimeResult = await IncidentModel.aggregate([ + { $match: { ...matchStage, status: false, endTime: { $exists: true, $ne: null } } }, + { $project: { resolutionTime: { $subtract: ["$endTime", "$startTime"] } } }, + { $group: { _id: null, avgResolutionTime: { $avg: "$resolutionTime" } } }, + ]); + const avgResolutionTimeMs = resolutionTimeResult[0]?.avgResolutionTime || 0; + const avgResolutionTimeHours = Math.round((avgResolutionTimeMs / (1000 * 60 * 60) || 0) * 100) / 100; + + const monitorResult = await IncidentModel.aggregate([ + { $match: matchStage }, + { $group: { _id: "$monitorId", count: { $sum: 1 } } }, + { $sort: { count: -1 } }, + { $limit: 1 }, + { + $lookup: { + from: "monitors", + localField: "_id", + foreignField: "_id", + as: "monitor", + }, + }, + { $project: { monitorId: "$_id", count: 1, monitorName: { $arrayElemAt: ["$monitor.name", 0] } } }, + ]); + + const latestLimit = Math.max(1, Number.isFinite(Number(limit)) ? Number(limit) : 10); + const latestIncidents = await IncidentModel.aggregate([ + { $match: matchStage }, + { $sort: { createdAt: -1 } }, + { $limit: latestLimit }, + { + $lookup: { + from: "monitors", + localField: "monitorId", + foreignField: "_id", + as: "monitor", + }, + }, + { + $project: { + _id: 1, + monitorId: 1, + monitorName: { $arrayElemAt: ["$monitor.name", 0] }, + status: 1, + startTime: 1, + endTime: 1, + resolutionType: 1, + message: 1, + statusCode: 1, + createdAt: 1, + }, + }, + ]); + + return { + total, + totalActive: active, + totalManualResolutions: manual, + totalAutomaticResolutions: automatic, + avgResolutionTimeHours, + topMonitor: monitorResult[0] + ? { + monitorId: this.toStringId(monitorResult[0].monitorId), + monitorName: monitorResult[0].monitorName ?? null, + incidentCount: monitorResult[0].count, + } + : null, + latestIncidents: latestIncidents.map((incident) => ({ + id: this.toStringId(incident._id), + monitorId: this.toStringId(incident.monitorId), + monitorName: incident.monitorName ?? null, + status: incident.status, + startTime: this.toDateString(incident.startTime), + endTime: incident.endTime ? this.toDateString(incident.endTime) : null, + resolutionType: incident.resolutionType ?? null, + message: incident.message ?? null, + statusCode: incident.statusCode ?? null, + createdAt: this.toDateString(incident.createdAt), + })), + }; + }; +} +export default MongoIncidentRepository; diff --git a/server/src/repositories/index.ts b/server/src/repositories/index.ts index 44d64f5bb..72dfd2f40 100644 --- a/server/src/repositories/index.ts +++ b/server/src/repositories/index.ts @@ -6,3 +6,24 @@ export { default as MongoChecksRepository } from "@/repositories/checks/MongoChe export * from "@/repositories/monitor-stats/IMonitorStatsRepository.js"; export { default as MongoMonitorStatsRepository } from "@/repositories/monitor-stats/MongoMonitorStatsRepository.js"; + +export * from "@/repositories/status-pages/IStatusPagesRepository.js"; +export { default as MongoStatusPagesRepository } from "@/repositories/status-pages/MongoStatusPagesRepository.js"; + +export * from "@/repositories/users/IUsersRepository.js"; +export { default as MongoUsersRepository } from "@/repositories/users/MongoUsersRepository.js"; + +export * from "@/repositories/invites/IInvitesRepository.js"; +export { default as MongoInvitesRepository } from "@/repositories/invites/MongoInviteRepository.js"; + +export * from "@/repositories/recovery-tokens/IRecoveryTokensRepository.js"; +export { default as MongoRecoveryTokensRepository } from "@/repositories/recovery-tokens/MongoRecoveryTokensRepository.js"; + +export * from "@/repositories/settings/ISettingsRepository.js"; +export { default as MongoSettingsRepository } from "@/repositories/settings/MongoSettingsRepository.js"; + +export * from "@/repositories/notifications/INotificationsRepository.js"; +export { default as MongoNotificationsRepository } from "@/repositories/notifications/MongoNotificationsRepository.js"; + +export * from "@/repositories/incidents/IIncidentsRepository.js"; +export { default as MongoIncidentRepository } from "@/repositories/incidents/MongoIncidentRepository.js"; diff --git a/server/src/repositories/invites/IInvitesRepository.ts b/server/src/repositories/invites/IInvitesRepository.ts new file mode 100644 index 000000000..74a7ad68c --- /dev/null +++ b/server/src/repositories/invites/IInvitesRepository.ts @@ -0,0 +1,13 @@ +import type { Invite } from "@/types/index.js"; + +export interface IInvitesRepository { + // create + create(invite: Partial): Promise; + // fetch + findByToken(token: string): Promise; + findByTokenAndDelete(token: string): Promise; + // update + + // delete + // other +} diff --git a/server/src/repositories/invites/MongoInviteRepository.ts b/server/src/repositories/invites/MongoInviteRepository.ts new file mode 100644 index 000000000..e9243e96e --- /dev/null +++ b/server/src/repositories/invites/MongoInviteRepository.ts @@ -0,0 +1,63 @@ +import { IInvitesRepository } from "@/repositories/index.js"; +import type { Invite } from "@/types/index.js"; +import { type InviteDocument, InviteModel } from "@/db/models/index.js"; +import { AppError } from "@/utils/AppError.js"; +import mongoose from "mongoose"; +import crypto from "crypto"; + +class MongoInvitesRepository implements IInvitesRepository { + private toStringId = (value?: mongoose.Types.ObjectId | string | null): string => { + if (!value) { + return ""; + } + return value instanceof mongoose.Types.ObjectId ? value.toString() : String(value); + }; + + private toDateString = (value?: Date | string | null): string => { + if (!value) { + return new Date(0).toISOString(); + } + return value instanceof Date ? value.toISOString() : new Date(value).toISOString(); + }; + + protected toEntity = (doc: InviteDocument): Invite => { + return { + id: this.toStringId(doc._id), + email: doc.email, + teamId: this.toStringId(doc.teamId), + role: doc.role ?? [], + token: doc.token, + expiry: this.toDateString(doc.expiry), + createdAt: this.toDateString(doc.createdAt), + updatedAt: this.toDateString(doc.updatedAt), + }; + }; + + create = async (invite: Partial) => { + await InviteModel.deleteMany({ email: invite.email }); + invite.token = crypto.randomBytes(32).toString("hex"); + let inviteToken = await InviteModel.create(invite); + return this.toEntity(inviteToken); + }; + + findByToken = async (token: string) => { + const invite = await InviteModel.findOne({ + token, + }); + if (invite === null) { + throw new AppError({ message: "Invite not found", status: 404 }); + } + return this.toEntity(invite); + }; + + findByTokenAndDelete = async (token: string) => { + const invite = await InviteModel.findOneAndDelete({ + token, + }); + if (invite === null) { + throw new AppError({ message: "Invite not found", status: 404 }); + } + return this.toEntity(invite); + }; +} +export default MongoInvitesRepository; diff --git a/server/src/repositories/monitor-stats/IMonitorStatsRepository.ts b/server/src/repositories/monitor-stats/IMonitorStatsRepository.ts index a0720619f..08309b4ee 100644 --- a/server/src/repositories/monitor-stats/IMonitorStatsRepository.ts +++ b/server/src/repositories/monitor-stats/IMonitorStatsRepository.ts @@ -5,5 +5,6 @@ export interface IMonitorStatsRepository { findByMonitorId(monitorId: string): Promise; // update // delete + deleteByMonitorId(monitorId: string): Promise; // other } diff --git a/server/src/repositories/monitor-stats/MongoMonitorStatsRepository.ts b/server/src/repositories/monitor-stats/MongoMonitorStatsRepository.ts index d1d6a4825..52dbe8aa5 100644 --- a/server/src/repositories/monitor-stats/MongoMonitorStatsRepository.ts +++ b/server/src/repositories/monitor-stats/MongoMonitorStatsRepository.ts @@ -39,6 +39,14 @@ class MongoMonitorStatsRepository implements IMonitorStatsRepository { } return this.toEntity(monitorStats); }; + + deleteByMonitorId = async (monitorId: string) => { + const deleted = await MonitorStatsModel.findOneAndDelete({ monitorId: new mongoose.Types.ObjectId(monitorId) }); + if (!deleted) { + throw new AppError({ message: "Monitor stats not found", status: 404 }); + } + return this.toEntity(deleted); + }; } export default MongoMonitorStatsRepository; diff --git a/server/src/repositories/monitors/IMonitorsRepository.ts b/server/src/repositories/monitors/IMonitorsRepository.ts index 0da9c7279..29ebe37be 100644 --- a/server/src/repositories/monitors/IMonitorsRepository.ts +++ b/server/src/repositories/monitors/IMonitorsRepository.ts @@ -10,21 +10,33 @@ export interface TeamQueryConfig { order?: "asc" | "desc"; } +export interface SummaryConfig { + type?: MonitorType | MonitorType[]; +} + export interface IMonitorsRepository { // create create(monitor: Monitor, teamId: string, userId: string): Promise; createBulkMonitors(monitors: Monitor[]): Promise; // single fetch - findById(monitorId: string, teamId?: string): Promise; + findById(monitorId: string, teamId: string): Promise; // collection fetch findAll(): Promise; findByTeamId(teamId: string, config: TeamQueryConfig): Promise; + findByIds(monitorIds: string[]): Promise; + // update - update(monitorId: string, updates: Partial): Promise; + updateById(monitorId: string, teamId: string, updates: Partial): Promise; + togglePauseById(monitorId: string, teamId: string): Promise; // delete + deleteById(monitorId: string, teamId: string): Promise; deleteByTeamId(teamId: string): Promise<{ monitors: Monitor[]; deletedCount: number }>; // counts findMonitorCountByTeamIdAndType(teamId: string, config: TeamQueryConfig): Promise; + + // other + findMonitorsSummaryByTeamId(teamId: string, config?: SummaryConfig): Promise; + findGroupsByTeamId(teamId: string): Promise; } diff --git a/server/src/repositories/monitors/MongoMonitorsRepository.ts b/server/src/repositories/monitors/MongoMonitorsRepository.ts index c9af6668d..878d6f7cf 100644 --- a/server/src/repositories/monitors/MongoMonitorsRepository.ts +++ b/server/src/repositories/monitors/MongoMonitorsRepository.ts @@ -1,8 +1,8 @@ import { MonitorModel } from "@/db/models/index.js"; -import type { MonitorDocument } from "@/db/models/Monitor.js"; -import type { Monitor, MonitorType } from "@/types/monitor.js"; +import type { MonitorDocument } from "@/db/models/index.js"; +import type { Monitor } from "@/types/index.js"; import mongoose, { type FilterQuery } from "mongoose"; -import type { IMonitorsRepository, TeamQueryConfig } from "./IMonitorsRepository.js"; +import type { IMonitorsRepository, TeamQueryConfig, SummaryConfig } from "./IMonitorsRepository.js"; import { AppError } from "@/utils/AppError.js"; class MongoMonitorsRepository implements IMonitorsRepository { @@ -21,19 +21,11 @@ class MongoMonitorsRepository implements IMonitorsRepository { return this.mapDocuments(inserted); }; - findById = async (monitorId: string, teamId?: string): Promise => { - const match: { _id: string; teamId?: string } = { _id: monitorId }; - if (teamId) { - match.teamId = teamId; - } + findById = async (monitorId: string, teamId: string): Promise => { + const match: { _id: string; teamId: string } = { _id: monitorId, teamId }; const monitor = await MonitorModel.findOne(match); if (!monitor) { - if (monitor === null || monitor === undefined) { - throw new AppError({ - message: `Monitor with ID ${monitorId} not found.`, - status: 404, - }); - } + throw new AppError({ message: `Monitor with ID ${monitorId} not found`, status: 404 }); } return this.toEntity(monitor); }; @@ -44,7 +36,7 @@ class MongoMonitorsRepository implements IMonitorsRepository { }; findByTeamId = async (teamId: string, config: TeamQueryConfig): Promise => { - const { page = 0, rowsPerPage = 25, filter, field = "createdAt", order = "desc", type, limit } = config ?? {}; + const { page = 0, rowsPerPage = 0, filter, field = "createdAt", order = "desc", type, limit } = config ?? {}; const query: Record = { teamId: new mongoose.Types.ObjectId(teamId), @@ -75,13 +67,18 @@ class MongoMonitorsRepository implements IMonitorsRepository { const sort = { [field]: order === "asc" ? 1 : -1 } as const; const skip = Math.max(page, 0) * rowsPerPage; - const limitValue = limit ?? rowsPerPage; - const documents = await MonitorModel.find(query).sort(sort).skip(skip).limit(limitValue).exec(); + const documents = await MonitorModel.find(query).sort(sort).skip(skip).limit(rowsPerPage); return this.mapDocuments(documents); }; + findByIds = async (monitorIds: string[]): Promise => { + const objectIds = monitorIds.map((id) => new mongoose.Types.ObjectId(id)); + const monitors = await MonitorModel.find({ _id: { $in: objectIds } }); + return this.mapDocuments(monitors); + }; + findMonitorCountByTeamIdAndType = async (teamId: string, config?: TeamQueryConfig): Promise => { const { type } = config ?? {}; @@ -97,9 +94,9 @@ class MongoMonitorsRepository implements IMonitorsRepository { return count; }; - update = async (monitorId: string, patch: Partial) => { + updateById = async (monitorId: string, teamId: string, patch: Partial) => { const updatedMonitor = await MonitorModel.findOneAndUpdate( - { _id: monitorId }, + { _id: monitorId, teamId }, { $set: { ...patch, @@ -113,6 +110,35 @@ class MongoMonitorsRepository implements IMonitorsRepository { return this.toEntity(updatedMonitor); }; + togglePauseById = async (monitorId: string, teamId: string) => { + const monitor = await MonitorModel.findOneAndUpdate( + { _id: monitorId, teamId }, + [ + { + $set: { + isActive: { $not: "$isActive" }, + status: "$$REMOVE", + }, + }, + ], + { new: true } + ); + if (!monitor) { + throw new AppError({ message: `Monitor with ID ${monitorId} not found for the given team.`, status: 404 }); + } + return this.toEntity(monitor); + }; + + deleteById = async (monitorId: string, teamId: string) => { + const deletedMonitor = await MonitorModel.findOneAndDelete({ _id: monitorId, teamId }); + + if (!deletedMonitor) { + throw new AppError({ message: `Monitor with ID ${monitorId} not found for the given team.`, status: 404 }); + } + + return this.toEntity(deletedMonitor); + }; + deleteByTeamId = async (teamId: string) => { const monitors = await MonitorModel.find({ teamId }); const { deletedCount } = await MonitorModel.deleteMany({ teamId }); @@ -120,6 +146,52 @@ class MongoMonitorsRepository implements IMonitorsRepository { return { monitors: this.mapDocuments(monitors), deletedCount }; }; + findMonitorsSummaryByTeamId = async ( + teamId: string, + config?: SummaryConfig + ): Promise<{ totalMonitors: number; upMonitors: number; downMonitors: number; pausedMonitors: number }> => { + const match: FilterQuery = { teamId: new mongoose.Types.ObjectId(teamId) }; + if (config?.type !== undefined) { + match.type = Array.isArray(config.type) ? { $in: config.type } : config.type; + } + const pipeline = [ + { $match: match }, + { + $group: { + _id: null, + totalMonitors: { $sum: 1 }, + upMonitors: { + $sum: { + $cond: [{ $eq: ["$status", true] }, 1, 0], + }, + }, + downMonitors: { + $sum: { + $cond: [{ $eq: ["$status", false] }, 1, 0], + }, + }, + pausedMonitors: { + $sum: { + $cond: [{ $eq: ["$isActive", false] }, 1, 0], + }, + }, + }, + }, + { $project: { _id: 0 } }, + ]; + + const [summary] = await MonitorModel.aggregate(pipeline); + return summary ?? { totalMonitors: 0, upMonitors: 0, downMonitors: 0, pausedMonitors: 0 }; + }; + + findGroupsByTeamId = async (teamId: string): Promise => { + const groups = await MonitorModel.distinct("group", { + teamId: new mongoose.Types.ObjectId(teamId), + group: { $nin: [null, ""] }, + }); + return groups.sort(); + }; + private mapDocuments = (documents: MonitorDocument[]): Monitor[] => { if (!documents?.length) { return []; diff --git a/server/src/repositories/notifications/INotificationsRepository.ts b/server/src/repositories/notifications/INotificationsRepository.ts new file mode 100644 index 000000000..8bb65769a --- /dev/null +++ b/server/src/repositories/notifications/INotificationsRepository.ts @@ -0,0 +1,8 @@ +import type { Notification } from "@/types/index.js"; +export interface INotificationsRepository { + // create + // fetch + findNotificationsByIds(ids: string[]): Promise; + // update + // delete +} diff --git a/server/src/repositories/notifications/MongoNotificationsRepository.ts b/server/src/repositories/notifications/MongoNotificationsRepository.ts new file mode 100644 index 000000000..01a514f1c --- /dev/null +++ b/server/src/repositories/notifications/MongoNotificationsRepository.ts @@ -0,0 +1,46 @@ +import mongoose from "mongoose"; +import { NotificationModel, type NotificationDocument } from "@/db/models/index.js"; +import { INotificationsRepository } from "@/repositories/index.js"; +import type { Notification } from "@/types/index.js"; + +class MongoNotificationsRepository implements INotificationsRepository { + private mapDocuments = (documents: NotificationDocument[]): Notification[] => { + if (!documents?.length) { + return []; + } + return documents.map((doc) => this.toEntity(doc)); + }; + + private toEntity = (doc: NotificationDocument): Notification => { + const toStringId = (value: mongoose.Types.ObjectId | string): string => { + return value instanceof mongoose.Types.ObjectId ? value.toString() : value; + }; + + const toDateString = (value: Date | string): string => { + return value instanceof Date ? value.toISOString() : value; + }; + + return { + id: toStringId(doc._id), + userId: toStringId(doc.userId), + teamId: toStringId(doc.teamId), + type: doc.type, + notificationName: doc.notificationName, + address: doc.address ?? undefined, + phone: doc.phone ?? undefined, + homeserverUrl: doc.homeserverUrl ?? undefined, + roomId: doc.roomId ?? undefined, + accessToken: doc.accessToken ?? undefined, + createdAt: toDateString(doc.createdAt), + updatedAt: toDateString(doc.updatedAt), + }; + }; + + findNotificationsByIds = async (ids: string[]) => { + const mongoIds = ids.map((id) => new mongoose.Types.ObjectId(id)); + const documents = await NotificationModel.find({ _id: { $in: mongoIds } }); + return this.mapDocuments(documents); + }; +} + +export default MongoNotificationsRepository; diff --git a/server/src/repositories/recovery-tokens/IRecoveryTokensRepository.ts b/server/src/repositories/recovery-tokens/IRecoveryTokensRepository.ts new file mode 100644 index 000000000..9df1fa793 --- /dev/null +++ b/server/src/repositories/recovery-tokens/IRecoveryTokensRepository.ts @@ -0,0 +1,12 @@ +import type { RecoveryToken } from "@/types/recoveryToken.js"; + +export interface IRecoveryTokensRepository { + // create + create(email: string): Promise; + // fetch + findByToken(token: string): Promise; + // update + // delete + deleteManyByEmail(email: string): Promise; + // other +} diff --git a/server/src/repositories/recovery-tokens/MongoRecoveryTokensRepository.ts b/server/src/repositories/recovery-tokens/MongoRecoveryTokensRepository.ts new file mode 100644 index 000000000..4c9f9ebb6 --- /dev/null +++ b/server/src/repositories/recovery-tokens/MongoRecoveryTokensRepository.ts @@ -0,0 +1,61 @@ +import type { RecoveryToken } from "@/types/index.js"; +import type { IRecoveryTokensRepository } from "./IRecoveryTokensRepository.js"; +import type { RecoveryTokenDocument } from "@/db/models/RecoveryToken.js"; +import { RecoveryTokenModel } from "@/db/models/RecoveryToken.js"; +import mongoose from "mongoose"; +import crypto from "crypto"; +import { AppError } from "@/utils/AppError.js"; +const SERVICE_NAME = "MongoRecoveryTokensRepository"; + +class MongoRecoveryTokensRepository implements IRecoveryTokensRepository { + static SERVICE_NAME = SERVICE_NAME; + private toStringId = (value?: mongoose.Types.ObjectId | string | null): string => { + if (!value) { + return ""; + } + return value instanceof mongoose.Types.ObjectId ? value.toString() : String(value); + }; + + private toDateString = (value?: Date | string | null): string => { + if (!value) { + return new Date(0).toISOString(); + } + return value instanceof Date ? value.toISOString() : new Date(value).toISOString(); + }; + + protected toEntity = (doc: RecoveryTokenDocument): RecoveryToken => { + return { + id: this.toStringId(doc._id), + email: doc.email, + token: doc.token, + expiry: this.toDateString(doc.expiry), + createdAt: this.toDateString(doc.createdAt), + updatedAt: this.toDateString(doc.updatedAt), + }; + }; + + create = async (email: string): Promise => { + const token = await RecoveryTokenModel.create({ + email, + token: crypto.randomBytes(32).toString("hex"), + }); + return this.toEntity(token); + }; + + findByToken = async (token: string): Promise => { + const recoveryToken = await RecoveryTokenModel.findOne({ token }); + if (!recoveryToken) { + throw new AppError({ message: "Recovery token not found", service: SERVICE_NAME, status: 404 }); + } + return this.toEntity(recoveryToken); + }; + + deleteManyByEmail = async (email: string) => { + const result = await RecoveryTokenModel.deleteMany({ + email, + }); + return Promise.resolve(result.deletedCount || 0); + }; +} + +export default MongoRecoveryTokensRepository; diff --git a/server/src/repositories/settings/ISettingsRepository.ts b/server/src/repositories/settings/ISettingsRepository.ts new file mode 100644 index 000000000..111a92a55 --- /dev/null +++ b/server/src/repositories/settings/ISettingsRepository.ts @@ -0,0 +1,8 @@ +import type { Settings } from "@/types/index.js"; +export interface ISettingsRepository { + // create + // fetch + // update + update(settings: Partial): Promise; + // delete +} diff --git a/server/src/repositories/settings/MongoSettingsRepository.ts b/server/src/repositories/settings/MongoSettingsRepository.ts new file mode 100644 index 000000000..2cc700525 --- /dev/null +++ b/server/src/repositories/settings/MongoSettingsRepository.ts @@ -0,0 +1,76 @@ +import mongoose from "mongoose"; +import { ISettingsRepository } from "@/repositories/settings/ISettingsRepository.js"; +import type { Settings } from "@/types/index.js"; +import { AppSettingsModel, type AppSettingsDocument } from "@/db/models/AppSettings.js"; + +class MongoSettingsRepository implements ISettingsRepository { + private toStringId = (value?: mongoose.Types.ObjectId | string | null): string => { + if (!value) { + return ""; + } + return value instanceof mongoose.Types.ObjectId ? value.toString() : String(value); + }; + + private toDateString = (value?: Date | string | null): string => { + if (!value) { + return new Date(0).toISOString(); + } + return value instanceof Date ? value.toISOString() : new Date(value).toISOString(); + }; + + protected toEntity = (doc: AppSettingsDocument): Settings => { + return { + id: this.toStringId(doc._id), + checkTTL: doc.checkTTL, + language: doc.language, + jwtSecret: doc.jwtSecret ?? undefined, + pagespeedApiKey: doc.pagespeedApiKey ?? undefined, + systemEmailHost: doc.systemEmailHost ?? undefined, + systemEmailPort: doc.systemEmailPort ?? undefined, + systemEmailAddress: doc.systemEmailAddress ?? undefined, + systemEmailPassword: doc.systemEmailPassword ?? undefined, + systemEmailUser: doc.systemEmailUser ?? undefined, + systemEmailConnectionHost: doc.systemEmailConnectionHost ?? undefined, + systemEmailTLSServername: doc.systemEmailTLSServername ?? undefined, + systemEmailSecure: doc.systemEmailSecure ?? false, + systemEmailPool: doc.systemEmailPool ?? false, + systemEmailIgnoreTLS: doc.systemEmailIgnoreTLS ?? false, + systemEmailRequireTLS: doc.systemEmailRequireTLS ?? false, + systemEmailRejectUnauthorized: doc.systemEmailRejectUnauthorized ?? true, + showURL: doc.showURL ?? false, + singleton: doc.singleton, + version: doc.version ?? 1, + globalThresholds: doc.globalThresholds ?? undefined, + createdAt: this.toDateString(doc.createdAt), + updatedAt: this.toDateString(doc.updatedAt), + }; + }; + + update = async (settings: Partial) => { + const update: Record = { $set: { ...settings } }; + + if (settings.pagespeedApiKey === "") { + update.$unset = { pagespeedApiKey: "" }; + delete update.$set.pagespeedApiKey; + } + + if (settings.systemEmailPassword === "") { + update.$unset = { systemEmailPassword: "" }; + delete update.$set.systemEmailPassword; + } + + await AppSettingsModel.findOneAndUpdate({}, update, { + upsert: true, + }); + + const updatedSettings = await AppSettingsModel.findOneAndUpdate({}, update, { + upsert: true, + new: true, + projection: "-__v -_id -createdAt -updatedAt -singleton", + }); + + return this.toEntity(updatedSettings); + }; +} + +export default MongoSettingsRepository; diff --git a/server/src/repositories/status-pages/IStatusPagesRepository.ts b/server/src/repositories/status-pages/IStatusPagesRepository.ts new file mode 100644 index 000000000..1b9f9303b --- /dev/null +++ b/server/src/repositories/status-pages/IStatusPagesRepository.ts @@ -0,0 +1,11 @@ +import type { StatusPage } from "@/types/statusPage.js"; + +export interface IStatusPagesRepository { + // create + // single fetch + // collection fetch + // update + // delete + // other + removeMonitorFromStatusPages(monitorId: string): Promise; +} diff --git a/server/src/repositories/status-pages/MongoStatusPagesRepository.ts b/server/src/repositories/status-pages/MongoStatusPagesRepository.ts new file mode 100644 index 000000000..e1eb4715b --- /dev/null +++ b/server/src/repositories/status-pages/MongoStatusPagesRepository.ts @@ -0,0 +1,65 @@ +import { IStatusPagesRepository } from "@/repositories/index.js"; +import { type StatusPageDocument, StatusPageModel } from "@/db/models/StatusPage.js"; +import type { StatusPage, StatusPageLogo } from "@/types/statusPage.js"; +import mongoose from "mongoose"; + +class MongoStatusPagesRepository implements IStatusPagesRepository { + private toStringId = (value?: mongoose.Types.ObjectId | string | null): string => { + if (!value) { + return ""; + } + return value instanceof mongoose.Types.ObjectId ? value.toString() : String(value); + }; + + private toDateString = (value?: Date | string | null): string => { + if (!value) { + return new Date(0).toISOString(); + } + return value instanceof Date ? value.toISOString() : new Date(value).toISOString(); + }; + + private mapIdArray = (values?: Array): string[] => { + return values?.map((value) => this.toStringId(value)) ?? []; + }; + + private mapLogo = (logo?: StatusPageLogo | null): StatusPageLogo | undefined => { + if (!logo) { + return undefined; + } + return { + data: logo.data, + contentType: logo.contentType, + }; + }; + + private toEntity = (doc: StatusPageDocument): StatusPage => { + return { + id: this.toStringId(doc._id), + userId: this.toStringId(doc.userId), + teamId: this.toStringId(doc.teamId), + type: doc.type, + companyName: doc.companyName, + url: doc.url, + timezone: doc.timezone ?? undefined, + color: doc.color, + monitors: this.mapIdArray(doc.monitors), + subMonitors: this.mapIdArray(doc.subMonitors), + originalMonitors: this.mapIdArray(doc.originalMonitors), + logo: this.mapLogo(doc.logo), + isPublished: doc.isPublished, + showCharts: doc.showCharts, + showUptimePercentage: doc.showUptimePercentage, + showAdminLoginLink: doc.showAdminLoginLink, + customCSS: doc.customCSS, + createdAt: this.toDateString(doc.createdAt), + updatedAt: this.toDateString(doc.updatedAt), + }; + }; + + removeMonitorFromStatusPages = async (monitorId: string): Promise => { + const res = await StatusPageModel.updateMany({ monitors: monitorId }, { $pull: { monitors: monitorId } }); + return res.modifiedCount; + }; +} + +export default MongoStatusPagesRepository; diff --git a/server/src/repositories/users/IUsersRepository.ts b/server/src/repositories/users/IUsersRepository.ts new file mode 100644 index 000000000..3fa094c54 --- /dev/null +++ b/server/src/repositories/users/IUsersRepository.ts @@ -0,0 +1,15 @@ +import type { User } from "@/types/index.js"; +export interface IUsersRepository { + // create + create(user: Partial, imageFile?: Express.Multer.File | null): Promise; + // fetch + findByEmail(email: string): Promise; + findById(id: string): Promise; + findAll(): Promise; + // update + updateById(id: string, patch: Partial, file?: Express.Multer.File | null): Promise; + // delete + deleteById(id: string): Promise; + // other + findSuperAdmin(): Promise; +} diff --git a/server/src/repositories/users/MongoUsersRepository.ts b/server/src/repositories/users/MongoUsersRepository.ts new file mode 100644 index 000000000..023e8aefb --- /dev/null +++ b/server/src/repositories/users/MongoUsersRepository.ts @@ -0,0 +1,154 @@ +import mongoose from "mongoose"; +import { IUsersRepository } from "@/repositories/index.js"; +import { UserModel, type UserDocument } from "@/db/models/index.js"; +import type { User, UserProfileImage } from "@/types/index.js"; +import { GenerateAvatarImage } from "@/utils/imageProcessing.js"; +import { ParseBoolean } from "@/utils/utils.js"; +import { AppError } from "@/utils/AppError.js"; +const SERVICE_NAME = "MongoUsersRepository"; + +class MongoUsersRepository implements IUsersRepository { + static SERVICE_NAME = SERVICE_NAME; + private toStringId = (value?: mongoose.Types.ObjectId | string | null): string => { + if (!value) { + return ""; + } + return value instanceof mongoose.Types.ObjectId ? value.toString() : String(value); + }; + + private toDateString = (value?: Date | string | null): string => { + if (!value) { + return new Date(0).toISOString(); + } + return value instanceof Date ? value.toISOString() : new Date(value).toISOString(); + }; + + private mapProfileImage = (image?: (UserProfileImage & { data?: Buffer }) | null) => { + if (!image) { + return undefined; + } + return { + data: image.data, + contentType: image.contentType, + }; + }; + + protected toEntity = (doc: UserDocument): User => { + return { + id: this.toStringId(doc._id), + firstName: doc.firstName, + lastName: doc.lastName, + email: doc.email, + password: doc.password, + avatarImage: doc.avatarImage ?? undefined, + profileImage: this.mapProfileImage(doc.profileImage), + isActive: doc.isActive ?? false, + isVerified: doc.isVerified ?? false, + role: doc.role ?? [], + teamId: this.toStringId(doc.teamId), + checkTTL: doc.checkTTL ?? undefined, + createdAt: this.toDateString(doc.createdAt), + updatedAt: this.toDateString(doc.updatedAt), + }; + }; + + create = async (user: Partial, imageFile: Express.Multer.File | null) => { + if (imageFile) { + // 1. Save the full size image + user.profileImage = { + data: imageFile.buffer, + contentType: imageFile.mimetype, + }; + + // 2. Get the avatar sized image + const avatar = await GenerateAvatarImage(imageFile); + user.avatarImage = avatar; + } + + const newUser = new UserModel(user); + await newUser.save(); + const sanitizedUser = await UserModel.findOne({ _id: newUser._id }).select("-password").select("-profileImage"); + if (!sanitizedUser) { + throw new AppError({ message: "Failed to create user", service: SERVICE_NAME, status: 500 }); + } + return this.toEntity(sanitizedUser); + }; + + findByEmail = async (email: string) => { + const user = await UserModel.findOne({ email: email }).select("-profileImage"); + if (!user) { + throw new AppError({ message: "User not found", service: SERVICE_NAME, status: 404 }); + } + return this.toEntity(user); + }; + + findById = async (id: string) => { + const user = await UserModel.findById(id).select("-password").select("-profileImage"); + if (!user) { + throw new Error("User not found"); + } + + return this.toEntity(user); + }; + + findAll = async () => { + const users = await UserModel.find().select("-password").select("-profileImage"); + return this.mapDocuments(users); + }; + + updateById = async (id: string, patch: Partial, file?: Express.Multer.File | null): Promise => { + const candidateUser = { ...patch }; + + if (ParseBoolean(candidateUser.deleteProfileImage) === true) { + candidateUser.profileImage = undefined; + candidateUser.avatarImage = undefined; + } else if (file) { + // 1. Save the full size image + candidateUser.profileImage = { + data: file.buffer, + contentType: file.mimetype, + }; + + // 2. Get the avatar sized image + const avatar = await GenerateAvatarImage(file); + candidateUser.avatarImage = avatar; + } + + const updatedUser = await UserModel.findOneAndUpdate( + { _id: id }, + candidateUser, + { new: true } // Returns updated user instead of pre-update user + ) + .select("-password") + .select("-profileImage"); + if (!updatedUser) { + throw new AppError({ message: "User not found", service: SERVICE_NAME, status: 404 }); + } + return this.toEntity(updatedUser); + }; + + deleteById = async (id: string) => { + const deletedUser = await UserModel.findByIdAndDelete(id); + if (!deletedUser) { + throw new AppError({ message: "User not found", service: SERVICE_NAME, status: 404 }); + } + return this.toEntity(deletedUser); + }; + + findSuperAdmin = async () => { + const superAdmin = await UserModel.findOne({ role: "superadmin" }); + if (superAdmin !== null) { + return true; + } + return false; + }; + + private mapDocuments = (documents: UserDocument[]): User[] => { + if (!documents?.length) { + return []; + } + return documents.map((doc) => this.toEntity(doc)); + }; +} + +export default MongoUsersRepository; diff --git a/server/src/routes/v1/checkRoute.js b/server/src/routes/v1/checkRoute.js index 78f6b8a42..6565425d4 100755 --- a/server/src/routes/v1/checkRoute.js +++ b/server/src/routes/v1/checkRoute.js @@ -14,13 +14,8 @@ class CheckRoutes { 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.put("/check/:checkId", this.checkController.ackCheck); - this.router.get("/:monitorId", this.checkController.getChecksByMonitor); this.router.delete("/:monitorId", this.checkController.deleteChecks); - - this.router.put("/:path/:monitorId?", this.checkController.ackAllChecks); } getRouter() { diff --git a/server/src/routes/v1/monitorRoute.ts b/server/src/routes/v1/monitorRoute.ts index 24bc64ec8..2e6db630d 100755 --- a/server/src/routes/v1/monitorRoute.ts +++ b/server/src/routes/v1/monitorRoute.ts @@ -19,7 +19,6 @@ class MonitorRoutes { // Team routes this.router.get("/team", this.monitorController.getMonitorsByTeamId); this.router.get("/team/with-checks", this.monitorController.getMonitorsWithChecksByTeamId); - this.router.get("/team/summary", this.monitorController.getMonitorsAndSummaryByTeamId); this.router.get("/team/groups", this.monitorController.getGroupsByTeamId); // Uptime routes @@ -44,7 +43,6 @@ class MonitorRoutes { // Other static routes this.router.post("/demo", isAllowed(["admin", "superadmin"]), this.monitorController.addDemoMonitors); - this.router.get("/export", isAllowed(["admin", "superadmin"]), this.monitorController.exportMonitorsToCSV); this.router.get("/export/json", isAllowed(["admin", "superadmin"]), this.monitorController.exportMonitorsToJSON); this.router.post("/bulk", isAllowed(["admin", "superadmin"]), upload.single("csvFile"), this.monitorController.createBulkMonitors); this.router.post("/test-email", isAllowed(["admin", "superadmin"]), this.monitorController.sendTestEmail); diff --git a/server/src/service/business/checkService.js b/server/src/service/business/checkService.js deleted file mode 100644 index 9beb43326..000000000 --- a/server/src/service/business/checkService.js +++ /dev/null @@ -1,149 +0,0 @@ -const SERVICE_NAME = "checkService"; - -class CheckService { - static SERVICE_NAME = SERVICE_NAME; - - constructor({ db, settingsService, stringService, errorService }) { - this.db = db; - this.settingsService = settingsService; - this.stringService = stringService; - this.errorService = errorService; - } - - get serviceName() { - return CheckService.SERVICE_NAME; - } - - getChecksByMonitor = async ({ monitorId, query, teamId }) => { - if (!monitorId) { - throw this.errorService.createBadRequestError("No monitor ID in request"); - } - - if (!teamId) { - throw this.errorService.createBadRequestError("No team ID in request"); - } - - const monitor = await this.db.monitorModule.getMonitorById(monitorId); - - if (!monitor) { - throw this.errorService.createNotFoundError("Monitor not found"); - } - - if (!monitor.teamId.equals(teamId)) { - throw this.errorService.createAuthorizationError(); - } - - let { sortOrder, dateRange, filter, ack, page, rowsPerPage, status } = query; - const result = await this.db.checkModule.getChecksByMonitor({ - monitorId, - sortOrder, - dateRange, - filter, - ack, - page, - rowsPerPage, - status, - }); - return result; - }; - - getChecksByTeam = async ({ teamId, query }) => { - let { sortOrder, dateRange, filter, ack, page, rowsPerPage } = query; - - if (!teamId) { - throw this.errorService.createBadRequestError("No team ID in request"); - } - - const checkData = await this.db.checkModule.getChecksByTeam({ - sortOrder, - dateRange, - filter, - ack, - page, - rowsPerPage, - teamId, - }); - return checkData; - }; - - getChecksSummaryByTeamId = async ({ teamId }) => { - if (!teamId) { - throw this.errorService.createBadRequestError("No team ID in request"); - } - - const summary = await this.db.checkModule.getChecksSummaryByTeamId({ teamId }); - return summary; - }; - - ackCheck = async ({ checkId, teamId, ack }) => { - if (!checkId) { - throw this.errorService.createBadRequestError("No check ID in request"); - } - - if (!teamId) { - throw this.errorService.createBadRequestError("No team ID in request"); - } - - const updatedCheck = await this.db.checkModule.ackCheck(checkId, teamId, ack); - return updatedCheck; - }; - - ackAllChecks = async ({ monitorId, path, teamId, ack }) => { - if (path === "monitor") { - if (!monitorId) { - throw this.errorService.createBadRequestError("No monitor ID in request"); - } - - const monitor = await this.db.monitorModule.getMonitorById(monitorId); - if (!monitor) { - throw this.errorService.createNotFoundError("Monitor not found"); - } - - if (!monitor.teamId.equals(teamId)) { - throw this.errorService.createAuthorizationError(); - } - } - - const updatedChecks = await this.db.checkModule.ackAllChecks(monitorId, teamId, ack, path); - return updatedChecks; - }; - - deleteChecks = async ({ monitorId, teamId }) => { - if (!monitorId) { - throw this.errorService.createBadRequestError("No monitor ID in request"); - } - - if (!teamId) { - throw this.errorService.createBadRequestError("No team ID in request"); - } - - const monitor = await this.db.monitorModule.getMonitorById(monitorId); - - if (!monitor) { - throw this.errorService.createNotFoundError("Monitor not found"); - } - - if (!monitor.teamId.equals(teamId)) { - throw this.errorService.createAuthorizationError(); - } - - const deletedCount = await this.db.checkModule.deleteChecks(monitorId); - return deletedCount; - }; - deleteChecksByTeamId = async ({ teamId }) => { - if (!teamId) { - throw this.errorService.createBadRequestError("No team ID in request"); - } - - const deletedCount = await this.db.checkModule.deleteChecksByTeamId(teamId); - return deletedCount; - }; - - updateChecksTTL = async ({ teamId, ttl }) => { - const SECONDS_PER_DAY = 86400; - const newTTL = parseInt(ttl, 10) * SECONDS_PER_DAY; - await this.db.checkModule.updateChecksTTL(teamId, newTTL); - }; -} - -export default CheckService; diff --git a/server/src/service/business/checkService.ts b/server/src/service/business/checkService.ts new file mode 100644 index 000000000..3a932ed3f --- /dev/null +++ b/server/src/service/business/checkService.ts @@ -0,0 +1,186 @@ +import { IChecksRepository, IMonitorsRepository } from "@/repositories/index.js"; +import type { MonitorType, MonitorStatusResponse, CheckErrorInfo, Check } from "@/types/index.js"; +import type { HardwareStatusPayload, PageSpeedStatusPayload } from "@/types/network.js"; +import { AppError } from "@/utils/AppError.js"; +import { ParseBoolean } from "@/utils/utils.js"; + +const SERVICE_NAME = "checkService"; + +class CheckService { + static SERVICE_NAME = SERVICE_NAME; + + private errorService: any; + private monitorsRepository: IMonitorsRepository; + private checksRepository: IChecksRepository; + private logger: any; + constructor({ + errorService, + monitorsRepository, + logger, + checksRepository, + }: { + errorService: any; + monitorsRepository: IMonitorsRepository; + logger: any; + checksRepository: IChecksRepository; + }) { + this.errorService = errorService; + this.monitorsRepository = monitorsRepository; + this.logger = logger; + this.checksRepository = checksRepository; + } + + get serviceName() { + return CheckService.SERVICE_NAME; + } + + createChecks = async (checks: Check[]) => { + return this.checksRepository.createChecks(checks); + }; + + buildCheck = (statusResponse: MonitorStatusResponse) => { + const { monitorId, teamId, type, status, responseTime, code, message, payload, timings } = statusResponse; + + const check: Partial = { + metadata: { + monitorId, + teamId, + type, + }, + status, + statusCode: code, + responseTime: responseTime || 0, + timings: timings, + message, + }; + + if (type === "pagespeed") { + const pageSpeedPayload = payload as PageSpeedStatusPayload | undefined; + if (!pageSpeedPayload) { + this.logger.warn({ + message: "Failed to build check", + service: SERVICE_NAME, + method: "buildCheck", + details: "empty payload", + }); + return undefined; + } + const categories = pageSpeedPayload.lighthouseResult?.categories ?? {}; + const audits = pageSpeedPayload.lighthouseResult?.audits ?? {}; + const mapAudit = (audit: any) => { + if (!audit || typeof audit !== "object") { + return undefined; + } + return { + id: audit.id, + title: audit.title, + score: typeof audit.score === "number" ? audit.score : (audit.score ?? null), + displayValue: audit.displayValue, + numericValue: typeof audit.numericValue === "number" ? audit.numericValue : undefined, + numericUnit: audit.numericUnit, + }; + }; + check.accessibility = (categories?.accessibility?.score || 0) * 100; + check.bestPractices = (categories?.["best-practices"]?.score || 0) * 100; + check.seo = (categories?.seo?.score || 0) * 100; + check.performance = (categories?.performance?.score || 0) * 100; + check.audits = { + cls: mapAudit(audits?.["cumulative-layout-shift"]), + si: mapAudit(audits?.["speed-index"]), + fcp: mapAudit(audits?.["first-contentful-paint"]), + lcp: mapAudit(audits?.["largest-contentful-paint"]), + tbt: mapAudit(audits?.["total-blocking-time"]), + }; + } + + if (type === "hardware") { + const hardwarePayload = payload as HardwareStatusPayload | undefined; + const { cpu, memory, disk, host, net } = hardwarePayload?.data ?? {}; + const errorsSource = Array.isArray(hardwarePayload?.errors) + ? hardwarePayload?.errors + : (hardwarePayload?.errors as { errors?: CheckErrorInfo[] } | undefined)?.errors; + check.cpu = cpu; + check.memory = memory; + check.disk = disk; + check.host = host; + check.errors = errorsSource; + check.capture = hardwarePayload?.capture; + check.net = net; + } + return check; + }; + + getChecksByMonitor = async ({ monitorId, query, teamId }: { monitorId: string; query: any; teamId: string }) => { + if (!monitorId) { + throw this.errorService.createBadRequestError("No monitor ID in request"); + } + + if (!teamId) { + throw this.errorService.createBadRequestError("No team ID in request"); + } + + // For verificaiton, throws an error if monitor doesn't belong to team + await this.monitorsRepository.findById(monitorId, teamId); + + let { sortOrder, dateRange, filter, page, rowsPerPage, status } = query; + const parsedStatus = typeof status === "undefined" ? status : ParseBoolean(status); + const parsedPage = page ? parseInt(page) : page; + const parsedRowsPerPage = rowsPerPage ? parseInt(rowsPerPage) : rowsPerPage; + + const result = await this.checksRepository.findByMonitorId(monitorId, sortOrder, dateRange, filter, parsedPage, parsedRowsPerPage, parsedStatus); + + return result; + }; + + getChecksByTeam = async ({ teamId, query }: { teamId: string; query: any }) => { + let { sortOrder, dateRange, filter, page, rowsPerPage } = query; + + if (!teamId) { + throw this.errorService.createBadRequestError("No team ID in request"); + } + + const parsedPage = page ? parseInt(page) : page; + const parsedRowsPerPage = rowsPerPage ? parseInt(rowsPerPage) : rowsPerPage; + + const checkData = await this.checksRepository.findByTeamId(sortOrder, dateRange, filter, parsedPage, parsedRowsPerPage, teamId); + return checkData; + }; + + getChecksSummaryByTeamId = async ({ teamId }: { teamId: string }) => { + if (!teamId) { + throw this.errorService.createBadRequestError("No team ID in request"); + } + const summary = await this.checksRepository.findSummaryByTeamId(teamId); + return summary; + }; + + deleteChecks = async ({ monitorId, teamId }: { monitorId: string; teamId: string }) => { + if (!monitorId) { + throw this.errorService.createBadRequestError("No monitor ID in request"); + } + + if (!teamId) { + throw this.errorService.createBadRequestError("No team ID in request"); + } + + // For verificaiton, throws an error if monitor doesn't belong to team + await this.monitorsRepository.findById(monitorId, teamId); + + const deletedCount = await this.checksRepository.deleteByMonitorId(monitorId); + return deletedCount; + }; + deleteChecksByTeamId = async ({ teamId }: { teamId: string }) => { + if (!teamId) { + throw this.errorService.createBadRequestError("No team ID in request"); + } + + const deletedCount = await this.checksRepository.deleteByTeamId(teamId); + return deletedCount; + }; + + updateChecksTTL = async ({ teamId, ttl }: { teamId: string; ttl: string }) => { + throw new AppError({ message: "Not implemented", service: SERVICE_NAME, method: "updateChecksTTL", status: 500 }); + }; +} + +export default CheckService; diff --git a/server/src/service/business/diagnosticService.js b/server/src/service/business/diagnosticService.ts similarity index 88% rename from server/src/service/business/diagnosticService.js rename to server/src/service/business/diagnosticService.ts index 353604932..6c49933a4 100644 --- a/server/src/service/business/diagnosticService.js +++ b/server/src/service/business/diagnosticService.ts @@ -3,6 +3,14 @@ import os from "os"; const SERVICE_NAME = "diagnosticService"; +interface MemoryUsageMetrics { + rss: number; + heapTotal: number; + heapUsed: number; + external: number; + arrayBuffers: number; +} + class DiagnosticService { static SERVICE_NAME = SERVICE_NAME; @@ -47,8 +55,8 @@ class DiagnosticService { }; const used = process.memoryUsage(); - const memoryUsage = {}; - for (let key in used) { + const memoryUsage: Record = {}; + for (const key of Object.keys(used) as Array) { memoryUsage[`${key}Mb`] = Math.round((used[key] / 1024 / 1024) * 100) / 100; // MB } @@ -70,7 +78,7 @@ class DiagnosticService { performance.mark("end"); performance.measure("eventLoopDelay", "start", "end"); const entries = performance.getEntriesByName("eventLoopDelay"); - if (entries.length > 0) { + if (entries.length > 0 && entries[0] !== undefined) { eventLoopDelay = entries[0].duration; } diff --git a/server/src/service/business/incidentService.js b/server/src/service/business/incidentService.js deleted file mode 100644 index 71e60d279..000000000 --- a/server/src/service/business/incidentService.js +++ /dev/null @@ -1,414 +0,0 @@ -const SERVICE_NAME = "incidentService"; - -class IncidentService { - static SERVICE_NAME = SERVICE_NAME; - - constructor({ db, logger, errorService, stringService }) { - this.db = db; - this.logger = logger; - this.errorService = errorService; - this.stringService = stringService; - } - - get serviceName() { - return IncidentService.SERVICE_NAME; - } - - createIncident = async (monitor, check) => { - try { - if (!monitor || !monitor._id) { - throw this.errorService.createBadRequestError("Monitor is required"); - } - - if (!check || !check._id) { - throw this.errorService.createBadRequestError("Check is required"); - } - - const activeIncident = await this.db.incidentModule.getActiveIncidentByMonitor(monitor._id); - - if (activeIncident) { - await this.db.incidentModule.addCheckToIncident(activeIncident._id, check._id); - - this.logger.info({ - service: this.SERVICE_NAME, - method: "createIncident", - message: `Check added to existing active incident for monitor ${monitor.name}`, - incidentId: activeIncident._id, - monitorId: monitor._id, - }); - - return activeIncident; - } - - const incidentData = { - monitorId: monitor._id, - teamId: monitor.teamId, - type: monitor.type, - startTime: new Date(), - status: true, - message: check.message || null, - statusCode: check.statusCode || null, - checks: [check._id], - }; - - const incident = await this.db.incidentModule.createIncident(incidentData); - - this.logger.info({ - service: this.SERVICE_NAME, - method: "createIncident", - message: `New incident created for monitor ${monitor.name}`, - incidentId: incident._id, - monitorId: monitor._id, - }); - - return incident; - } catch (error) { - this.logger.error({ - service: this.SERVICE_NAME, - method: "createIncident", - message: error.message, - monitorId: monitor?._id, - error: error.stack, - }); - throw error; - } - }; - - resolveIncident = async (monitor, check) => { - try { - if (!monitor || !monitor._id) { - throw this.errorService.createBadRequestError("Monitor is required"); - } - - const activeIncident = await this.db.incidentModule.getActiveIncidentByMonitor(monitor._id); - - if (!activeIncident) { - this.logger.info({ - service: this.SERVICE_NAME, - method: "resolveIncident", - message: `No active incident found for monitor ${monitor.name}`, - monitorId: monitor._id, - }); - return null; - } - - await this.db.incidentModule.addCheckToIncident(activeIncident._id, check._id); - - const resolvedIncident = await this.db.incidentModule.resolveIncident(activeIncident._id, { - resolutionType: "automatic", - resolvedBy: null, - endTime: new Date(), - }); - - this.logger.info({ - service: this.SERVICE_NAME, - method: "resolveIncident", - message: `Incident automatically resolved for monitor ${monitor.name}`, - incidentId: resolvedIncident._id, - monitorId: monitor._id, - }); - - return resolvedIncident; - } catch (error) { - this.logger.error({ - service: this.SERVICE_NAME, - method: "resolveIncident", - message: error.message, - monitorId: monitor?._id, - error: error.stack, - }); - throw error; - } - }; - - resolveIncidentManually = async ({ incidentId, userId, teamId, comment }) => { - try { - if (!incidentId) { - throw this.errorService.createBadRequestError("No incident ID in request"); - } - - if (!userId) { - throw this.errorService.createBadRequestError("No user ID in request"); - } - - if (!teamId) { - throw this.errorService.createBadRequestError("No team ID in request"); - } - - const incident = await this.db.incidentModule.getIncidentById(incidentId); - - if (!incident) { - throw this.errorService.createNotFoundError("Incident not found"); - } - - if (!incident.teamId.equals(teamId)) { - throw this.errorService.createAuthorizationError(); - } - - if (incident.status === false) { - throw this.errorService.createBadRequestError("Incident is already resolved"); - } - - const resolvedIncident = await this.db.incidentModule.resolveIncident(incidentId, { - resolutionType: "manual", - resolvedBy: userId, - comment: comment || null, - endTime: new Date(), - }); - - this.logger.info({ - service: this.SERVICE_NAME, - method: "resolveIncidentManually", - message: `Incident manually resolved by user`, - incidentId: resolvedIncident._id, - userId, - }); - - return resolvedIncident; - } catch (error) { - this.logger.error({ - service: this.SERVICE_NAME, - method: "resolveIncidentManually", - message: error.message, - incidentId, - error: error.stack, - }); - throw error; - } - }; - - getIncidentsByTeam = async ({ teamId, query }) => { - try { - if (!teamId) { - throw this.errorService.createBadRequestError("No team ID in request"); - } - - const { sortOrder, dateRange, page, rowsPerPage, status, monitorId, resolutionType } = query || {}; - - const result = await this.db.incidentModule.getIncidentsByTeam({ - teamId, - sortOrder, - dateRange, - page, - rowsPerPage, - status, - monitorId, - resolutionType, - }); - - return result; - } catch (error) { - this.logger.error({ - service: this.SERVICE_NAME, - method: "getIncidentsByTeam", - message: error.message, - teamId, - error: error.stack, - }); - throw error; - } - }; - - getIncidentSummary = async ({ teamId, query }) => { - try { - if (!teamId) { - throw this.errorService.createBadRequestError("No team ID in request"); - } - - const { limit } = query || {}; - - const summary = await this.db.incidentModule.getIncidentSummary({ - teamId, - limit, - }); - - return summary; - } catch (error) { - this.logger.error({ - service: this.SERVICE_NAME, - method: "getIncidentSummary", - message: error.message, - teamId, - error: error.stack, - }); - throw error; - } - }; - - getIncidentById = async ({ incidentId, teamId }) => { - try { - if (!incidentId) { - throw this.errorService.createBadRequestError("No incident ID in request"); - } - - if (!teamId) { - throw this.errorService.createBadRequestError("No team ID in request"); - } - - const incident = await this.db.incidentModule.getIncidentById(incidentId); - - if (!incident) { - throw this.errorService.createNotFoundError("Incident not found"); - } - - if (!incident.teamId.equals(teamId)) { - throw this.errorService.createAuthorizationError(); - } - - return incident; - } catch (error) { - this.logger.error({ - service: this.SERVICE_NAME, - method: "getIncidentById", - message: error.message, - incidentId, - error: error.stack, - }); - throw error; - } - }; - - processIncidentsFromBuffer = async (incidentBufferItems) => { - try { - if (!incidentBufferItems || incidentBufferItems.length === 0) { - return; - } - - const createItems = []; - const resolveItems = []; - - for (const item of incidentBufferItems) { - if (item.action === "resolve") { - resolveItems.push(item); - } else { - createItems.push(item); - } - } - - for (const item of resolveItems) { - try { - await this.resolveIncident(item.monitor, item.check); - } catch (error) { - this.logger.error({ - service: this.SERVICE_NAME, - method: "processIncidentsFromBuffer", - message: `Failed to resolve incident from buffer: ${error.message}`, - monitorId: item.monitor?._id, - error: error.stack, - }); - } - } - - if (createItems.length === 0) { - return; - } - - const groupedByMonitor = {}; - for (const item of createItems) { - if (!item.monitor || !item.monitor._id || !item.check || !item.check._id) { - this.logger.warn({ - service: this.SERVICE_NAME, - method: "processIncidentsFromBuffer", - message: "Skipping item with missing monitor or check data", - item, - }); - continue; - } - - const monitorId = item.monitor._id.toString(); - if (!groupedByMonitor[monitorId]) { - groupedByMonitor[monitorId] = []; - } - groupedByMonitor[monitorId].push(item); - } - - const monitorIds = Object.keys(groupedByMonitor); - if (monitorIds.length === 0) { - return; - } - - const activeIncidents = await this.db.incidentModule.getActiveIncidentsByMonitors(monitorIds); - - const incidentsCreatedInFlush = {}; - const checksToAddToIncidents = []; - const newIncidentsToCreate = []; - - for (const [monitorId, items] of Object.entries(groupedByMonitor)) { - const existingIncident = activeIncidents.get(monitorId) || incidentsCreatedInFlush[monitorId]; - - if (existingIncident) { - const incidentId = existingIncident._id ? existingIncident._id.toString() : existingIncident; - for (const item of items) { - checksToAddToIncidents.push({ - incidentId, - checkId: item.check._id.toString(), - }); - } - } else { - const firstItem = items[0]; - const incidentData = { - monitorId: firstItem.monitor._id, - teamId: firstItem.monitor.teamId, - type: firstItem.monitor.type, - startTime: new Date(), - status: true, - message: firstItem.check.message || null, - statusCode: firstItem.check.statusCode || null, - checks: [firstItem.check._id], - }; - - newIncidentsToCreate.push({ - incidentData, - monitorId, - remainingChecks: items.slice(1), // Checks restantes para agregar después - }); - } - } - - if (newIncidentsToCreate.length > 0) { - const incidentDataArray = newIncidentsToCreate.map((item) => item.incidentData); - await this.db.incidentModule.createIncidents(incidentDataArray); - - const createdIncidentsMap = await this.db.incidentModule.getActiveIncidentsByMonitors(newIncidentsToCreate.map((item) => item.monitorId)); - - for (const item of newIncidentsToCreate) { - const createdIncident = createdIncidentsMap.get(item.monitorId); - if (createdIncident && createdIncident._id) { - const incidentId = createdIncident._id.toString(); - incidentsCreatedInFlush[item.monitorId] = incidentId; - - for (const remainingItem of item.remainingChecks) { - checksToAddToIncidents.push({ - incidentId, - checkId: remainingItem.check._id.toString(), - }); - } - } - } - } - - if (checksToAddToIncidents.length > 0) { - await this.db.incidentModule.addChecksToIncidentsBatch(checksToAddToIncidents); - } - - this.logger.info({ - service: this.SERVICE_NAME, - method: "processIncidentsFromBuffer", - message: `Processed ${incidentBufferItems.length} incident buffer items`, - created: newIncidentsToCreate.length, - checksAdded: checksToAddToIncidents.length, - resolved: resolveItems.length, - }); - } catch (error) { - this.logger.error({ - service: this.SERVICE_NAME, - method: "processIncidentsFromBuffer", - message: error.message, - error: error.stack, - }); - throw error; - } - }; -} - -export default IncidentService; diff --git a/server/src/service/business/incidentService.ts b/server/src/service/business/incidentService.ts new file mode 100644 index 000000000..82211bc4e --- /dev/null +++ b/server/src/service/business/incidentService.ts @@ -0,0 +1,225 @@ +const SERVICE_NAME = "incidentService"; +import type { Monitor } from "@/types/monitor.js"; +import { AppError } from "@/utils/AppError.js"; +import { ParseBoolean } from "@/utils/utils.js"; +import type { IIncidentsRepository } from "@/repositories/index.js"; +import type { Incident } from "@/types/index.js"; + +const dateRangeLookup: Record = { + recent: new Date(new Date().setDate(new Date().getDate() - 2)), + hour: new Date(new Date().setHours(new Date().getHours() - 1)), + day: new Date(new Date().setDate(new Date().getDate() - 1)), + week: new Date(new Date().setDate(new Date().getDate() - 7)), + month: new Date(new Date().setMonth(new Date().getMonth() - 1)), + all: undefined, +}; + +class IncidentService { + static SERVICE_NAME = SERVICE_NAME; + + private db: any; + private logger: any; + private errorService: any; + private stringService: any; + private incidentsRepository: IIncidentsRepository; + + constructor({ + db, + logger, + errorService, + stringService, + incidentsRepository, + }: { + db: any; + logger: any; + errorService: any; + stringService: any; + incidentsRepository: IIncidentsRepository; + }) { + this.db = db; + this.logger = logger; + this.errorService = errorService; + this.stringService = stringService; + this.incidentsRepository = incidentsRepository; + } + + get serviceName() { + return IncidentService.SERVICE_NAME; + } + + handleIncident = async (monitor: Monitor, code: number): Promise => { + const activeIncident = await this.incidentsRepository.findActiveByMonitorId(monitor.id, monitor.teamId); + // Monitor is down, create an incident + if (monitor.status === false) { + if (activeIncident) { + return activeIncident; + } else { + const incident = { + monitorId: monitor.id, + teamId: monitor.teamId, + startTime: Date.now().toString(), + status: true, + statusCode: code, + }; + return await this.incidentsRepository.create(incident); + } + } + + // Monitor is up, resolve active incidents + if (!activeIncident) { + return null; + } + activeIncident.status = false; + activeIncident.endTime = Date.now().toString(); + activeIncident.resolutionType = "automatic"; + return await this.incidentsRepository.updateById(activeIncident.id, activeIncident.teamId, activeIncident); + }; + + resolveIncident = async (incidentId: string, userId: string, teamId: string, comment?: string) => { + try { + if (!incidentId) { + throw new AppError({ message: "No incident ID in request", service: SERVICE_NAME, method: "resolveIncident" }); + } + + if (!userId) { + throw new AppError({ message: "No user ID in request", service: SERVICE_NAME, method: "resolveIncident" }); + } + + if (!teamId) { + throw new AppError({ message: "No team ID in request", service: SERVICE_NAME, method: "resolveIncident" }); + } + + const incident = await this.incidentsRepository.findActiveByIncidentId(incidentId, teamId); + + if (!incident) { + throw new AppError({ message: "Incident not found", service: SERVICE_NAME, method: "resolveIncident" }); + } + + if (incident.status === false) { + throw new AppError({ message: "Incident is already resolved", service: SERVICE_NAME, method: "resolveIncident" }); + } + + incident.resolutionType = "manual"; + incident.status = false; + incident.resolvedBy = userId; + incident.comment = comment || null; + incident.endTime = Date.now().toString(); + + const resolvedIncident = await this.incidentsRepository.updateById(incident.id, teamId, incident); + + this.logger.debug({ + service: SERVICE_NAME, + method: "resolveIncidentManually", + message: `Incident manually resolved by user`, + details: resolvedIncident.id, + }); + + return resolvedIncident; + } catch (error: any) { + this.logger.error({ + service: SERVICE_NAME, + method: "resolveIncident", + message: error.message, + details: incidentId, + stack: error.stack, + }); + throw error; + } + }; + + getIncidentsByTeam = async ({ teamId, query }: { teamId: string; query?: any }) => { + try { + if (!teamId) { + throw this.errorService.createBadRequestError("No team ID in request"); + } + + const { sortOrder, dateRange, page, rowsPerPage, status, monitorId, resolutionType } = query || {}; + const startDate = dateRangeLookup[dateRange]; + + const parsedPage = Number.isFinite(parseInt(page)) ? parseInt(page) : 0; + const parsedRowsPerPage = Number.isFinite(parseInt(rowsPerPage)) ? parseInt(rowsPerPage) : 20; + const parsedStatus = typeof status === "undefined" ? undefined : ParseBoolean(status); + + const incidents = await this.incidentsRepository.findByTeamId( + teamId, + startDate, + parsedPage, + parsedRowsPerPage, + sortOrder, + parsedStatus, + monitorId, + resolutionType + ); + + const count = await this.incidentsRepository.countByTeamId(teamId, startDate, parsedStatus, monitorId, resolutionType); + + return { incidents, count }; + } catch (error: any) { + this.logger.error({ + service: SERVICE_NAME, + method: "getIncidentsByTeam", + message: error.message, + details: teamId, + stack: error.stack, + }); + throw error; + } + }; + + getIncidentSummary = async (teamId: string, limit?: string) => { + try { + if (!teamId) { + throw this.errorService.createBadRequestError(" team ID in request"); + } + + const parsedLimit = limit && Number.isFinite(parseInt(limit, 10)) ? parseInt(limit, 10) : 10; + const summary = await this.incidentsRepository.findSummaryByTeamId(teamId, parsedLimit); + + return summary; + } catch (error: any) { + this.logger.error({ + service: SERVICE_NAME, + method: "getIncidentSummary", + message: error.message, + details: teamId, + stack: error.stack, + }); + throw error; + } + }; + + getIncidentById = async ({ incidentId, teamId }: { incidentId: string; teamId: string }) => { + try { + if (!incidentId) { + throw this.errorService.createBadRequestError("No incident ID in request"); + } + + if (!teamId) { + throw this.errorService.createBadRequestError("No team ID in request"); + } + + const incident = await this.db.incidentModule.getIncidentById(incidentId); + + if (!incident) { + throw this.errorService.createNotFoundError("Incident not found"); + } + + if (!incident.teamId.equals(teamId)) { + throw this.errorService.createAuthorizationError(); + } + + return incident; + } catch (error: any) { + this.logger.error({ + service: SERVICE_NAME, + method: "getIncidentById", + message: error.message, + details: incidentId, + stack: error.stack, + }); + throw error; + } + }; +} + +export default IncidentService; diff --git a/server/src/service/business/inviteService.js b/server/src/service/business/inviteService.js deleted file mode 100644 index 369ed195a..000000000 --- a/server/src/service/business/inviteService.js +++ /dev/null @@ -1,44 +0,0 @@ -const SERVICE_NAME = "inviteService"; - -class InviteService { - static SERVICE_NAME = SERVICE_NAME; - - constructor({ db, settingsService, emailService, stringService, errorService }) { - this.db = db; - this.settingsService = settingsService; - this.emailService = emailService; - this.stringService = stringService; - this.errorService = errorService; - } - - get serviceName() { - return InviteService.SERVICE_NAME; - } - - getInviteToken = async ({ invite, teamId }) => { - invite.teamId = teamId; - const inviteToken = await this.db.inviteModule.requestInviteToken(invite); - return inviteToken; - }; - - sendInviteEmail = async ({ inviteRequest, firstName }) => { - const inviteToken = await this.db.inviteModule.requestInviteToken({ ...inviteRequest }); - const { clientHost } = this.settingsService.getSettings(); - - const html = await this.emailService.buildEmail("employeeActivationTemplate", { - name: firstName, - link: `${clientHost}/register/${inviteToken.token}`, - }); - const result = await this.emailService.sendEmail(inviteRequest.email, "Welcome to Uptime Monitor", html); - if (!result) { - throw this.errorService.createServerError("Failed to send invite e-mail... Please verify your settings."); - } - }; - - verifyInviteToken = async ({ inviteToken }) => { - const invite = await this.db.inviteModule.getInviteToken(inviteToken); - return invite; - }; -} - -export default InviteService; diff --git a/server/src/service/business/inviteService.ts b/server/src/service/business/inviteService.ts new file mode 100644 index 000000000..cdb860fba --- /dev/null +++ b/server/src/service/business/inviteService.ts @@ -0,0 +1,60 @@ +import type { Invite } from "@/types/index.js"; +import type { IInvitesRepository } from "@/repositories/index.js"; + +const SERVICE_NAME = "inviteService"; + +class InviteService { + static SERVICE_NAME = SERVICE_NAME; + + private settingsService: any; + private emailService: any; + private errorService: any; + private invitesRepository: IInvitesRepository; + + constructor({ + invitesRepository, + settingsService, + emailService, + errorService, + }: { + invitesRepository: IInvitesRepository; + settingsService: any; + emailService: any; + errorService: any; + }) { + this.invitesRepository = invitesRepository; + this.settingsService = settingsService; + this.emailService = emailService; + this.errorService = errorService; + } + + get serviceName() { + return InviteService.SERVICE_NAME; + } + + getInviteToken = async ({ invite, teamId }: { invite: Partial; teamId: string }) => { + invite.teamId = teamId; + const inviteToken = await this.invitesRepository.create(invite); + return inviteToken; + }; + + sendInviteEmail = async ({ invite, firstName }: { invite: Partial; firstName: any }) => { + const inviteToken = await this.invitesRepository.create(invite); + const { clientHost } = this.settingsService.getSettings(); + + const html = await this.emailService.buildEmail("employeeActivationTemplate", { + name: firstName, + link: `${clientHost}/register/${inviteToken.token}`, + }); + const result = await this.emailService.sendEmail(invite.email, "Welcome to Uptime Monitor", html); + if (!result) { + throw this.errorService.createServerError("Failed to send invite e-mail... Please verify your settings."); + } + }; + + verifyInviteToken = async ({ inviteToken }: { inviteToken: string }) => { + return await this.invitesRepository.findByToken(inviteToken); + }; +} + +export default InviteService; diff --git a/server/src/service/business/maintenanceWindowService.js b/server/src/service/business/maintenanceWindowService.ts similarity index 55% rename from server/src/service/business/maintenanceWindowService.js rename to server/src/service/business/maintenanceWindowService.ts index 9d52702e9..bb82821cf 100644 --- a/server/src/service/business/maintenanceWindowService.js +++ b/server/src/service/business/maintenanceWindowService.ts @@ -1,30 +1,50 @@ +import { IMonitorsRepository } from "@/repositories/index.js"; + const SERVICE_NAME = "maintenanceWindowService"; class MaintenanceWindowService { static SERVICE_NAME = SERVICE_NAME; + private db: any; + private settingsService: any; + private stringService: any; + private errorService: any; + private monitorsRepository: IMonitorsRepository; - constructor({ db, settingsService, stringService, errorService }) { + constructor({ + db, + settingsService, + stringService, + errorService, + monitorsRepository, + }: { + db: any; + settingsService: any; + stringService: any; + errorService: any; + monitorsRepository: IMonitorsRepository; + }) { this.db = db; this.settingsService = settingsService; this.stringService = stringService; this.errorService = errorService; + this.monitorsRepository = monitorsRepository; } get serviceName() { return MaintenanceWindowService.SERVICE_NAME; } - createMaintenanceWindow = async ({ teamId, body }) => { + createMaintenanceWindow = async ({ teamId, body }: { teamId: string; body: any }) => { const monitorIds = body.monitors; - const monitors = await this.db.monitorModule.getMonitorsByIds(monitorIds); + const monitors = await this.monitorsRepository.findByIds(monitorIds); - const unauthorizedMonitors = monitors.filter((monitor) => !monitor.teamId.equals(teamId)); + const unauthorizedMonitors = monitors.filter((monitor) => monitor.teamId !== teamId); if (unauthorizedMonitors.length > 0) { throw this.errorService.createAuthorizationError(); } - const dbTransactions = monitorIds.map((monitorId) => { + const dbTransactions = monitorIds.map((monitorId: string) => { return this.db.maintenanceWindowModule.createMaintenanceWindow({ teamId, monitorId, @@ -38,26 +58,26 @@ class MaintenanceWindowService { await Promise.all(dbTransactions); }; - getMaintenanceWindowById = async ({ id, teamId }) => { + getMaintenanceWindowById = async ({ id, teamId }: { id: string; teamId: string }) => { const maintenanceWindow = await this.db.maintenanceWindowModule.getMaintenanceWindowById({ id, teamId }); return maintenanceWindow; }; - getMaintenanceWindowsByTeamId = async ({ teamId, query }) => { + getMaintenanceWindowsByTeamId = async ({ teamId, query }: { teamId: string; query: any }) => { const maintenanceWindows = await this.db.maintenanceWindowModule.getMaintenanceWindowsByTeamId(teamId, query); return maintenanceWindows; }; - getMaintenanceWindowsByMonitorId = async ({ monitorId, teamId }) => { + getMaintenanceWindowsByMonitorId = async ({ monitorId, teamId }: { monitorId: string; teamId: string }) => { const maintenanceWindows = await this.db.maintenanceWindowModule.getMaintenanceWindowsByMonitorId({ monitorId, teamId }); return maintenanceWindows; }; - deleteMaintenanceWindow = async ({ id, teamId }) => { + deleteMaintenanceWindow = async ({ id, teamId }: { id: string; teamId: string }) => { await this.db.maintenanceWindowModule.deleteMaintenanceWindowById({ id, teamId }); }; - editMaintenanceWindow = async ({ id, teamId, body }) => { + editMaintenanceWindow = async ({ id, teamId, body }: { id: string; teamId: string; body: any }) => { const editedMaintenanceWindow = await this.db.maintenanceWindowModule.editMaintenanceWindowById({ id, body, teamId }); return editedMaintenanceWindow; }; diff --git a/server/src/service/business/monitorService.ts b/server/src/service/business/monitorService.ts index 3793ac35e..fee3a9ffc 100644 --- a/server/src/service/business/monitorService.ts +++ b/server/src/service/business/monitorService.ts @@ -2,7 +2,7 @@ import { createMonitorsBodyValidation } from "@/validation/joi.js"; import { NormalizeData, NormalizeDataUptimeDetails } from "@/utils/dataUtils.js"; import { type Monitor } from "@/types/index.js"; import type { MonitorType } from "@/types/monitor.js"; -import type { IChecksRepository, IMonitorsRepository, IMonitorStatsRepository } from "@/repositories/index.js"; +import type { IChecksRepository, IMonitorsRepository, IMonitorStatsRepository, IStatusPagesRepository } from "@/repositories/index.js"; import fs from "fs"; import { fileURLToPath } from "url"; import path from "path"; @@ -14,7 +14,6 @@ type DateRangeKey = "recent" | "day" | "week" | "month" | "all"; export interface IMonitorService { readonly serviceName: string; - verifyTeamAccess(args: { teamId: string; monitorId: string }): Promise; // create createMonitor(teamId: string, userId: string, body: Monitor): Promise; @@ -36,7 +35,6 @@ export interface IMonitorService { field?: string; order?: "asc" | "desc"; }): Promise; - getMonitorsAndSummaryByTeamId(args: { teamId: string; type?: string | string[]; explain?: boolean }): Promise; getMonitorsWithChecksByTeamId(args: { teamId: string; limit?: number; @@ -47,21 +45,20 @@ export interface IMonitorService { field?: string; order?: "asc" | "desc"; explain?: boolean; - }): Promise<{ count: number; monitors: any[] }>; + }): Promise<{ summary: any; count: number; monitors: any[] }>; getAllGames(): any; - getGroupsByTeamId(args: { teamId: string }): Promise; + getGroupsByTeamId(args: { teamId: string }): Promise; // update - editMonitor(args: { teamId: string; monitorId: string; body: any }): Promise; - pauseMonitor(args: { teamId: string; monitorId: string }): Promise; + editMonitor(args: { teamId: string; monitorId: string; body: Monitor }): Promise; + pauseMonitor(args: { teamId: string; monitorId: string }): Promise; // delete - deleteMonitor(args: { teamId: string; monitorId: string }): Promise; + deleteMonitor(args: { teamId: string; monitorId: string }): Promise; deleteAllMonitors(args: { teamId: string }): Promise; // other sendTestEmail(args: { to: string }): Promise; - exportMonitorsToCSV(args: { teamId: string }): Promise; exportMonitorsToJSON(args: { teamId: string }): Promise; } @@ -79,9 +76,9 @@ export class MonitorService implements IMonitorService { private monitorsRepository: IMonitorsRepository; private checksRepository: IChecksRepository; private monitorStatsRepository: IMonitorStatsRepository; + private statusPagesRepository: IStatusPagesRepository; constructor({ - db, jobQueue, stringService, emailService, @@ -92,8 +89,8 @@ export class MonitorService implements IMonitorService { monitorsRepository, checksRepository, monitorStatsRepository, + statusPagesRepository, }: { - db: any; jobQueue: any; stringService: any; emailService: any; @@ -104,8 +101,8 @@ export class MonitorService implements IMonitorService { monitorsRepository: IMonitorsRepository; checksRepository: IChecksRepository; monitorStatsRepository: IMonitorStatsRepository; + statusPagesRepository: IStatusPagesRepository; }) { - this.db = db; this.jobQueue = jobQueue; this.stringService = stringService; this.emailService = emailService; @@ -116,6 +113,7 @@ export class MonitorService implements IMonitorService { this.monitorsRepository = monitorsRepository; this.checksRepository = checksRepository; this.monitorStatsRepository = monitorStatsRepository; + this.statusPagesRepository = statusPagesRepository; } get serviceName(): string { @@ -147,13 +145,6 @@ export class MonitorService implements IMonitorService { return formatLookup[dateRange]; }; - verifyTeamAccess = async ({ teamId, monitorId }: { teamId: string; monitorId: string }): Promise => { - const monitor = await this.db.monitorModule.getMonitorById(monitorId); - if (!monitor?.teamId?.equals(teamId)) { - throw this.errorService.createAuthorizationError(); - } - }; - createMonitor = async (teamId: string, userId: string, body: Monitor): Promise => { const monitor = await this.monitorsRepository.create(body, teamId, userId); if (!monitor) { @@ -256,15 +247,13 @@ export class MonitorService implements IMonitorService { dateRange: string; normalize?: boolean; }): Promise => { - await this.verifyTeamAccess({ teamId, monitorId }); - const monitor = await this.monitorsRepository.findById(monitorId, teamId); if (!monitor) { throw new AppError({ message: `Monitor with ID ${monitorId} not found.`, status: 404 }); } const rangeKey = (dateRange as DateRangeKey) ?? "recent"; const { start, end } = this.getDateRange(rangeKey); - const checksData = await this.checksRepository.findDateRangeChecksByMonitor(monitor.id, start, end, this.getDateFormat(rangeKey), { + const checksData = await this.checksRepository.findByDateRangeAndMonitorId(monitor.id, start, end, this.getDateFormat(rangeKey), { type: monitor.type, }); const monitorStats = await this.monitorStatsRepository.findByMonitorId(monitor.id); @@ -293,7 +282,6 @@ export class MonitorService implements IMonitorService { }; getHardwareDetailsById = async ({ teamId, monitorId, dateRange }: { teamId: string; monitorId: string; dateRange: string }): Promise => { - await this.verifyTeamAccess({ teamId, monitorId }); const monitor = await this.monitorsRepository.findById(monitorId, teamId); if (!monitor) { throw new AppError({ message: `Monitor with ID ${monitorId} not found.`, status: 404 }); @@ -304,7 +292,7 @@ export class MonitorService implements IMonitorService { const rangeKey = (dateRange as DateRangeKey) ?? "recent"; const { start, end } = this.getDateRange(rangeKey); - const checksData = await this.checksRepository.findDateRangeChecksByMonitor(monitor.id, start, end, this.getDateFormat(rangeKey), { + const checksData = await this.checksRepository.findByDateRangeAndMonitorId(monitor.id, start, end, this.getDateFormat(rangeKey), { type: monitor.type, }); @@ -325,7 +313,6 @@ export class MonitorService implements IMonitorService { }; getPageSpeedDetailsById = async ({ teamId, monitorId, dateRange }: { teamId: string; monitorId: string; dateRange: string }): Promise => { - await this.verifyTeamAccess({ teamId, monitorId }); const monitor = await this.monitorsRepository.findById(monitorId, teamId); if (!monitor) { throw new AppError({ message: `Monitor with ID ${monitorId} not found.`, status: 404 }); @@ -336,20 +323,25 @@ export class MonitorService implements IMonitorService { const rangeKey = (dateRange as DateRangeKey) ?? "recent"; const { start, end } = this.getDateRange(rangeKey); - const checksData = await this.checksRepository.findDateRangeChecksByMonitor(monitor.id, start, end, this.getDateFormat(rangeKey), { + const checksData = await this.checksRepository.findByDateRangeAndMonitorId(monitor.id, start, end, this.getDateFormat(rangeKey), { type: monitor.type, }); if (checksData.monitorType !== "pagespeed") { throw new AppError({ message: "Unable to load pagespeed stats for this monitor", status: 500 }); } + + const monitorStats = await this.monitorStatsRepository.findByMonitorId(monitor.id); + return { - ...monitor, - checks: checksData.checks, + monitor: { + ...monitor, + checks: checksData.checks, + }, + monitorStats, }; }; getMonitorById = async ({ teamId, monitorId }: { teamId: string; monitorId: string }): Promise => { - await this.verifyTeamAccess({ teamId, monitorId }); const monitor = await this.monitorsRepository.findById(monitorId, teamId); return monitor; }; @@ -362,23 +354,6 @@ export class MonitorService implements IMonitorService { return monitors; }; - getMonitorsAndSummaryByTeamId = async ({ - teamId, - type, - explain, - }: { - teamId: string; - type?: string | string[]; - explain?: boolean; - }): Promise => { - const result = await this.db.monitorModule.getMonitorsAndSummaryByTeamId({ - type, - explain, - teamId, - }); - return result; - }; - getMonitorsWithChecksByTeamId = async ({ teamId, limit, @@ -399,7 +374,8 @@ export class MonitorService implements IMonitorService { field?: string; order?: "asc" | "desc"; explain?: boolean; - }): Promise<{ count: number; monitors: any[] }> => { + }): Promise<{ summary: any; count: number; monitors: any[] }> => { + const summary = await this.monitorsRepository.findMonitorsSummaryByTeamId(teamId); const count = await this.monitorsRepository.findMonitorCountByTeamIdAndType(teamId, { type, filter }); const monitors = await this.monitorsRepository.findByTeamId(teamId, { limit, @@ -412,13 +388,13 @@ export class MonitorService implements IMonitorService { }); const monitorsList = (monitors ?? []) as Monitor[]; - const snapshotTypes: MonitorType[] = ["hardware", "pagespeed"]; + const snapshotTypes: MonitorType[] = ["hardware"]; const requestedTypes = Array.isArray(type) ? type : type ? [type] : []; const snapshotOnlyRequest = requestedTypes.length > 0 && requestedTypes.every((requestedType) => snapshotTypes.includes(requestedType as MonitorType)); const limitPerMonitor = snapshotOnlyRequest ? 1 : 25; - const checksMap = await this.checksRepository.findLatestChecksByMonitorIds( + const checksMap = await this.checksRepository.findLatestByMonitorIds( monitorsList.map((monitor) => monitor.id), { limitPerMonitor } ); @@ -433,36 +409,36 @@ export class MonitorService implements IMonitorService { }; }); - return { count, monitors: monitorsWithChecks }; + return { summary: summary ?? null, count, monitors: monitorsWithChecks }; }; getAllGames = (): any => { return this.games; }; - getGroupsByTeamId = async ({ teamId }: { teamId: string }): Promise => { - const groups = await this.db.monitorModule.getGroupsByTeamId({ teamId }); + getGroupsByTeamId = async ({ teamId }: { teamId: string }): Promise => { + const groups = await this.monitorsRepository.findGroupsByTeamId(teamId); return groups; }; - editMonitor = async ({ teamId, monitorId, body }: { teamId: string; monitorId: string; body: any }): Promise => { - await this.verifyTeamAccess({ teamId, monitorId }); - const editedMonitor = await this.db.monitorModule.editMonitor({ monitorId, body }); + editMonitor = async ({ teamId, monitorId, body }: { teamId: string; monitorId: string; body: Monitor }) => { + const editedMonitor = await this.monitorsRepository.updateById(monitorId, teamId, body); await this.jobQueue.updateJob(editedMonitor); + return editedMonitor; }; - pauseMonitor = async ({ teamId, monitorId }: { teamId: string; monitorId: string }): Promise => { - await this.verifyTeamAccess({ teamId, monitorId }); - const monitor = await this.db.monitorModule.pauseMonitor({ monitorId }); - monitor.isActive === true ? await this.jobQueue.resumeJob(monitor._id, monitor) : await this.jobQueue.pauseJob(monitor); + pauseMonitor = async ({ teamId, monitorId }: { teamId: string; monitorId: string }): Promise => { + const monitor = await this.monitorsRepository.togglePauseById(monitorId, teamId); + monitor.isActive === true ? await this.jobQueue.resumeJob(monitor) : await this.jobQueue.pauseJob(monitor); return monitor; }; - deleteMonitor = async ({ teamId, monitorId }: { teamId: string; monitorId: string }): Promise => { - await this.verifyTeamAccess({ teamId, monitorId }); - const monitor = await this.db.monitorModule.deleteMonitor({ teamId, monitorId }); + deleteMonitor = async ({ teamId, monitorId }: { teamId: string; monitorId: string }): Promise => { + const monitor = await this.monitorsRepository.deleteById(monitorId, teamId); + await this.monitorStatsRepository.deleteByMonitorId(monitor.id); + await this.checksRepository.deleteByMonitorId(monitor.id); + await this.statusPagesRepository.removeMonitorFromStatusPages(monitor.id); await this.jobQueue.deleteJob(monitor); - await this.db.statusPageModule.deleteStatusPagesByMonitorId(monitor._id); return monitor; }; @@ -472,9 +448,9 @@ export class MonitorService implements IMonitorService { monitors.map(async (monitor) => { try { await this.jobQueue.deleteJob(monitor); - await this.db.checkModule.deleteChecks(monitor.id); - await this.db.pageSpeedCheckModule.deletePageSpeedChecksByMonitorId(monitor.id); - await this.db.notificationsModule.deleteNotificationsByMonitorId(monitor.id); + await this.checksRepository.deleteByMonitorId(monitor.id); + await this.statusPagesRepository.removeMonitorFromStatusPages(monitor.id); + await this.monitorStatsRepository.deleteByMonitorId(monitor.id); } catch (error: any) { this.logger.warn({ message: `Error deleting associated records for monitor ${monitor.id} with name ${monitor.name}`, @@ -502,65 +478,13 @@ export class MonitorService implements IMonitorService { return messageId; }; - exportMonitorsToCSV = async ({ teamId }: { teamId: string }): Promise => { - const monitors = await this.db.monitorModule.getMonitorsByTeamId({ teamId }); - - if (!monitors || monitors.length === 0) { - throw this.errorService.createNotFoundError("No monitors to export"); - } - - const csvData = monitors?.filteredMonitors?.map((monitor: any) => ({ - name: monitor.name, - description: monitor.description, - type: monitor.type, - url: monitor.url, - interval: monitor.interval, - port: monitor.port, - ignoreTlsErrors: monitor.ignoreTlsErrors, - isActive: monitor.isActive, - })); - - const csv = this.papaparse.unparse(csvData); - return csv; - }; exportMonitorsToJSON = async ({ teamId }: { teamId: string }): Promise => { - const monitors = await this.db.monitorModule.getMonitorsByTeamId({ teamId }); + const monitors = await this.monitorsRepository.findByTeamId(teamId, {}); if (!monitors || monitors.length === 0) { throw this.errorService.createNotFoundError("No monitors to export"); } - const json = monitors?.filteredMonitors - ?.map((monitor: any) => { - const initialType = monitor.type; - let parsedType; - - if (initialType === "hardware") { - parsedType = "infrastructure"; - } else if (initialType === "http") { - if (monitor.url.startsWith("https://")) { - parsedType = "https"; - } else { - parsedType = "http"; - } - } else if (initialType === "pagespeed") { - parsedType = initialType; - } else { - // Skip unsupported types - return; - } - - return { - name: monitor.name, - url: monitor.url, - type: parsedType, - interval: monitor.interval, - n: monitor.statusWindowSize, - secret: monitor.secret, - }; - }) - .filter(Boolean); - - return json; + return monitors; }; } diff --git a/server/src/service/business/userService.js b/server/src/service/business/userService.js deleted file mode 100644 index 7d7f7b014..000000000 --- a/server/src/service/business/userService.js +++ /dev/null @@ -1,219 +0,0 @@ -const SERVICE_NAME = "userService"; - -class UserService { - static SERVICE_NAME = SERVICE_NAME; - - constructor({ crypto, db, emailService, settingsService, logger, stringService, jwt, errorService, jobQueue }) { - this.db = db; - this.emailService = emailService; - this.settingsService = settingsService; - this.logger = logger; - this.stringService = stringService; - this.jwt = jwt; - this.errorService = errorService; - this.jobQueue = jobQueue; - this.crypto = crypto; - } - - get serviceName() { - return UserService.SERVICE_NAME; - } - - issueToken = (payload, appSettings) => { - const tokenTTL = appSettings?.jwtTTL ?? "2h"; - const tokenSecret = appSettings?.jwtSecret; - const payloadData = payload; - return this.jwt.sign(payloadData, tokenSecret, { expiresIn: tokenTTL }); - }; - - registerUser = async (user, file) => { - // Create a new user - // If superAdmin exists, a token should be attached to all further register requests - const superAdminExists = await this.db.userModule.checkSuperadmin(); - if (superAdminExists) { - const invitedUser = await this.db.inviteModule.getInviteTokenAndDelete(user.inviteToken); - user.role = invitedUser.role; - user.teamId = invitedUser.teamId; - } else { - // This is the first account, create JWT secret to use if one is not supplied by env - const jwtSecret = this.crypto.randomBytes(64).toString("hex"); - await this.db.settingsModule.updateAppSettings({ jwtSecret }); - } - - const newUser = await this.db.userModule.insertUser({ ...user }, file); - - this.logger.debug({ - message: "New user created", - service: SERVICE_NAME, - method: "registerUser", - details: newUser._id, - }); - - const userForToken = { ...newUser._doc }; - delete userForToken.profileImage; - delete userForToken.avatarImage; - - const appSettings = await this.settingsService.getSettings(); - - const token = this.issueToken(userForToken, appSettings); - - try { - const html = await this.emailService.buildEmail("welcomeEmailTemplate", { - name: newUser.firstName, - }); - this.emailService.sendEmail(newUser.email, "Welcome to Uptime Monitor", html).catch((error) => { - this.logger.warn({ - message: error.message, - service: SERVICE_NAME, - method: "registerUser", - stack: error.stack, - }); - }); - } catch (error) { - this.logger.warn({ - message: error.message, - service: SERVICE_NAME, - method: "registerUser", - stack: error.stack, - }); - } - - return { user: newUser, token }; - }; - - loginUser = async (email, password) => { - // Check if user exists - const user = await this.db.userModule.getUserByEmail(email); - // Compare password - const match = await user.comparePassword(password); - if (match !== true) { - throw this.errorService.createAuthenticationError(this.stringService.authIncorrectPassword); - } - - // Remove password from user object. Should this be abstracted to DB layer? - const userWithoutPassword = { ...user._doc }; - delete userWithoutPassword.password; - delete userWithoutPassword.avatarImage; - - // Happy path, return token - const appSettings = await this.settingsService.getSettings(); - const token = this.issueToken(userWithoutPassword, appSettings); - // reset avatar image - userWithoutPassword.avatarImage = user.avatarImage; - return { user: userWithoutPassword, token }; - }; - - editUser = async (updates, file, currentUser) => { - // Change Password check - if (updates?.password && updates?.newPassword) { - // Get user's email - // Add user email to body for DB operation - updates.email = currentUser.email; - // Get user - const user = await this.db.userModule.getUserByEmail(currentUser.email); - // Compare passwords - const match = await user.comparePassword(updates?.password); - // If not a match, throw a 403 - // 403 instead of 401 to avoid triggering axios interceptor - if (!match) { - throw this.errorService.createAuthorizationError(this.stringService.authIncorrectPassword); - } - // If a match, update the password - updates.password = updates.newPassword; - } - - const updatedUser = await this.db.userModule.updateUser({ userId: currentUser?._id, user: updates, file: file }); - return updatedUser; - }; - - checkSuperadminExists = async () => { - const superAdminExists = await this.db.userModule.checkSuperadmin(); - return superAdminExists; - }; - - requestRecovery = async (email) => { - const user = await this.db.userModule.getUserByEmail(email); - const recoveryToken = await this.db.recoveryModule.requestRecoveryToken(email); - const name = user.firstName; - const { clientHost } = this.settingsService.getSettings(); - const url = `${clientHost}/set-new-password/${recoveryToken.token}`; - - const html = await this.emailService.buildEmail("passwordResetTemplate", { - name, - email, - url, - }); - const msgId = await this.emailService.sendEmail(email, "Checkmate Password Reset", html); - return msgId; - }; - - validateRecovery = async (recoveryToken) => { - await this.db.recoveryModule.validateRecoveryToken(recoveryToken); - }; - - resetPassword = async (password, recoveryToken) => { - const user = await this.db.recoveryModule.resetPassword(password, recoveryToken); - const appSettings = await this.settingsService.getSettings(); - const token = this.issueToken(user._doc, appSettings); - return { user, token }; - }; - - deleteUser = async (user) => { - const email = user?.email; - if (!email) { - throw this.errorService.createBadRequestError("No email in request"); - } - - const teamId = user?.teamId; - const userId = user?._id; - - if (!teamId) { - throw this.errorService.createBadRequestError("No team ID in request"); - } - - if (!userId) { - throw this.errorService.createBadRequestError("No user ID in request"); - } - - const roles = user?.role; - if (roles.includes("demo")) { - throw this.errorService.createBadRequestError("Demo user cannot be deleted"); - } - - // 1. Find all the monitors associated with the team ID if superadmin - const result = await this.db.monitorModule.getMonitorsByTeamId({ - teamId: teamId, - }); - - if (roles.includes("superadmin")) { - // 2. Remove all jobs, delete checks and alerts - result?.monitors.length > 0 && - (await Promise.all( - result.monitors.map(async (monitor) => { - await this.jobQueue.deleteJob(monitor); - }) - )); - } - // 6. Delete the user by id - await this.db.userModule.deleteUser(userId); - }; - - getAllUsers = async () => { - const users = await this.db.userModule.getAllUsers(); - return users; - }; - - getUserById = async (roles, userId) => { - const user = await this.db.userModule.getUserById(roles, userId); - return user; - }; - - editUserById = async (userId, user) => { - await this.db.userModule.editUserById(userId, user); - }; - setPasswordByUserId = async (userId, password) => { - const updatedUser = await this.db.userModule.updateUser({ userId: userId, user: { password: password }, file: null }); - return updatedUser; - }; -} -export default UserService; diff --git a/server/src/service/business/userService.ts b/server/src/service/business/userService.ts new file mode 100644 index 000000000..5f73508dd --- /dev/null +++ b/server/src/service/business/userService.ts @@ -0,0 +1,295 @@ +import { IInvitesRepository, IMonitorsRepository, IRecoveryTokensRepository, IUsersRepository, ISettingsRepository } from "@/repositories/index.js"; +import Team from "@/db/models/Team.js"; +import type { User } from "@/types/index.js"; +import bcrypt from "bcryptjs"; +import { AppError } from "@/utils/AppError.js"; + +const SERVICE_NAME = "userService"; + +class UserService { + static SERVICE_NAME = SERVICE_NAME; + + private emailService: any; + private settingsService: any; + private logger: any; + private stringService: any; + private jwt: any; + private errorService: any; + private jobQueue: any; + private crypto: any; + private monitorsRepository: IMonitorsRepository; + private usersRepository: IUsersRepository; + private invitesRepository: IInvitesRepository; + private recoveryTokensRepository: IRecoveryTokensRepository; + private settingsRepository: ISettingsRepository; + + constructor({ + crypto, + emailService, + settingsService, + logger, + stringService, + jwt, + errorService, + jobQueue, + monitorsRepository, + usersRepository, + invitesRepository, + recoveryTokensRepository, + settingsRepository, + }: { + crypto: any; + emailService: any; + settingsService: any; + logger: any; + stringService: any; + jwt: any; + errorService: any; + jobQueue: any; + monitorsRepository: IMonitorsRepository; + usersRepository: IUsersRepository; + invitesRepository: IInvitesRepository; + recoveryTokensRepository: IRecoveryTokensRepository; + settingsRepository: ISettingsRepository; + }) { + this.emailService = emailService; + this.settingsService = settingsService; + this.logger = logger; + this.stringService = stringService; + this.jwt = jwt; + this.errorService = errorService; + this.jobQueue = jobQueue; + this.crypto = crypto; + this.monitorsRepository = monitorsRepository; + this.usersRepository = usersRepository; + this.invitesRepository = invitesRepository; + this.recoveryTokensRepository = recoveryTokensRepository; + this.settingsRepository = settingsRepository; + } + + get serviceName() { + return UserService.SERVICE_NAME; + } + + issueToken = (payload: any, appSettings: any) => { + const tokenTTL = appSettings?.jwtTTL ?? "2h"; + const tokenSecret = appSettings?.jwtSecret; + const payloadData = payload; + return this.jwt.sign(payloadData, tokenSecret, { expiresIn: tokenTTL }); + }; + + registerUser = async (user: Partial, inviteToken: string, file: any) => { + // Create a new user + // If superAdmin exists, a token should be attached to all further register requests + const superAdminExists = await this.usersRepository.findSuperAdmin(); + if (superAdminExists) { + const invite = await this.invitesRepository.findByTokenAndDelete(inviteToken); + user.role = invite.role; + user.teamId = invite.teamId; + } else { + // This is the first account, create JWT secret to use if one is not supplied by env + const jwtSecret = this.crypto.randomBytes(64).toString("hex"); + await this.settingsRepository.update({ jwtSecret }); + // Create a new team + const team = new Team({ + email: user.email, + }); + user.teamId = team._id; + } + + const newUser = await this.usersRepository.create({ ...user }, file); + + this.logger.debug({ + message: "New user created", + service: SERVICE_NAME, + method: "registerUser", + details: newUser.id, + }); + + delete newUser.profileImage; + delete newUser.avatarImage; + + const appSettings = await this.settingsService.getSettings(); + + const token = this.issueToken(newUser, appSettings); + + try { + const html = await this.emailService.buildEmail("welcomeEmailTemplate", { + name: newUser.firstName, + }); + this.emailService.sendEmail(newUser.email, "Welcome to Uptime Monitor", html).catch((error: any) => { + this.logger.warn({ + message: error.message, + service: SERVICE_NAME, + method: "registerUser", + stack: error.stack, + }); + }); + } catch (error: any) { + this.logger.warn({ + message: error.message, + service: SERVICE_NAME, + method: "registerUser", + stack: error.stack, + }); + } + + return { user: newUser, token }; + }; + + loginUser = async (email: string, password: string) => { + // Check if user exists + const user = await this.usersRepository.findByEmail(email); + // Compare password + const match = await bcrypt.compare(password, user.password); + + if (match !== true) { + throw this.errorService.createAuthenticationError(this.stringService.authIncorrectPassword); + } + + // Remove password from user object. Should this be abstracted to DB layer? + const userWithoutPassword = { ...user }; + userWithoutPassword.password = ""; + userWithoutPassword.avatarImage = ""; + + // Happy path, return token + const appSettings = await this.settingsService.getSettings(); + const token = this.issueToken(userWithoutPassword, appSettings); + // reset avatar image + userWithoutPassword.avatarImage = user.avatarImage; + return { user: userWithoutPassword, token }; + }; + + editUser = async (updates: Partial, file: any, currentUser: any) => { + // Change Password check + if (updates?.password && updates?.newPassword) { + // Get user's email + // Add user email to body for DB operation + updates.email = currentUser.email; + // Get user + const user = await this.usersRepository.findByEmail(currentUser.email); + // Compare passwords + const match = await bcrypt.compare(updates?.password, user.password); + // If not a match, throw a 403 + // 403 instead of 401 to avoid triggering axios interceptor + if (!match) { + throw this.errorService.createAuthorizationError(this.stringService.authIncorrectPassword); + } + // If a match, update the password + updates.password = updates.newPassword; + } + + return await this.usersRepository.updateById(currentUser.id, updates, file); + }; + + checkSuperadminExists = async () => { + return await this.usersRepository.findSuperAdmin(); + }; + + requestRecovery = async (email: string) => { + const user = await this.usersRepository.findByEmail(email); + + // Delete existing tokens + await this.recoveryTokensRepository.deleteManyByEmail(email); + const recoveryToken = await this.recoveryTokensRepository.create(email); + const name = user.firstName; + const { clientHost } = this.settingsService.getSettings(); + const url = `${clientHost}/set-new-password/${recoveryToken.token}`; + + const html = await this.emailService.buildEmail("passwordResetTemplate", { + name, + email, + url, + }); + const msgId = await this.emailService.sendEmail(email, "Checkmate Password Reset", html); + return msgId; + }; + + validateRecovery = async (recoveryToken: string) => { + // Throws if token not found, validating + await this.recoveryTokensRepository.findByToken(recoveryToken); + }; + + resetPassword = async (password: string, recoveryToken: string) => { + const existingToken = await this.recoveryTokensRepository.findByToken(recoveryToken); + const existingUser = await this.usersRepository.findByEmail(existingToken.email); + + const match = await bcrypt.compare(password, existingUser.password); + if (match === true) { + throw new AppError({ message: "New password cannot be same as old password", service: SERVICE_NAME, status: 400 }); + } + + existingUser.password = password; + await this.usersRepository.updateById(existingUser.id, existingUser, null); + await this.recoveryTokensRepository.deleteManyByEmail(existingUser.email); + + existingUser.password = ""; + existingUser.profileImage = undefined; + + const token = this.issueToken(existingUser, await this.settingsService.getSettings()); + + return { user: existingUser, token }; + }; + + deleteUser = async (user: User) => { + const email = user?.email; + if (!email) { + throw this.errorService.createBadRequestError("No email in request"); + } + + const teamId = user?.teamId; + const userId = user?.id; + + if (!teamId) { + throw this.errorService.createBadRequestError("No team ID in request"); + } + + if (!userId) { + throw this.errorService.createBadRequestError("No user ID in request"); + } + + const roles = user?.role; + if (roles.includes("demo")) { + throw this.errorService.createBadRequestError("Demo user cannot be deleted"); + } + + // 1. Find all the monitors associated with the team ID if superadmin + const res = await this.monitorsRepository.findByTeamId(teamId, {}); + + if (roles.includes("superadmin")) { + // 2. Remove all jobs, delete checks and alerts + res && + res?.length > 0 && + (await Promise.all( + res.map(async (monitor) => { + await this.jobQueue.deleteJob(monitor); + }) + )); + } + // 6. Delete the user by id + await this.usersRepository.deleteById(userId); + }; + + getAllUsers = async () => { + return await this.usersRepository.findAll(); + }; + + getUserById = async (roles: any, userId: any) => { + if (!roles.includes("superadmin")) { + throw new AppError({ message: "User is not a superadmin", service: SERVICE_NAME, status: 403 }); + } + const user = await this.usersRepository.findById(userId); + + return user; + }; + + editUserById = async (userId: any, patch: Partial) => { + await this.usersRepository.updateById(userId, patch, null); + }; + + setPasswordByUserId = async (userId: any, password: string) => { + const updatedUser = await this.usersRepository.updateById(userId, { password }, null); + return updatedUser; + }; +} +export default UserService; diff --git a/server/src/service/index.ts b/server/src/service/index.ts index 4793f055b..7f7d0f14a 100644 --- a/server/src/service/index.ts +++ b/server/src/service/index.ts @@ -1 +1,13 @@ export * from "@/service/business/monitorService.js"; +export * from "@/service/infrastructure/networkService.js"; +export * from "@/service/infrastructure/notificationProviders/discord.js"; +export * from "@/service/infrastructure/notificationProviders/email.js"; +export * from "@/service/infrastructure/notificationProviders/INotificationProvider.js"; +export * from "@/service/infrastructure/notificationProviders/pagerduty.js"; +export * from "@/service/infrastructure/notificationProviders/matrix.js"; +export * from "@/service/infrastructure/notificationProviders/slack.js"; +export * from "@/service/infrastructure/notificationProviders/webhook.js"; +export * from "@/service/infrastructure/notificationsService.js"; +export * from "@/service/infrastructure/statusService.js"; +export * from "@/service/infrastructure/notificationProviders/webhook.js"; +export * from "@/service/infrastructure/notificationProviders/matrix.js"; diff --git a/server/src/service/infrastructure/SuperSimpleQueue/SuperSimpleQueue.js b/server/src/service/infrastructure/SuperSimpleQueue/SuperSimpleQueue.js deleted file mode 100644 index a6637d4cc..000000000 --- a/server/src/service/infrastructure/SuperSimpleQueue/SuperSimpleQueue.js +++ /dev/null @@ -1,177 +0,0 @@ -import Scheduler from "super-simple-scheduler"; -const SERVICE_NAME = "JobQueue"; - -class SuperSimpleQueue { - static SERVICE_NAME = SERVICE_NAME; - - constructor({ envSettings, db, logger, helper, monitorsRepository }) { - this.envSettings = envSettings; - this.db = db; - this.logger = logger; - this.helper = helper; - this.monitorsRepository = monitorsRepository; - } - - get serviceName() { - return SuperSimpleQueue.SERVICE_NAME; - } - - static async create({ envSettings, db, logger, helper, monitorsRepository }) { - const instance = new SuperSimpleQueue({ envSettings, db, logger, helper, monitorsRepository }); - await instance.init(); - return instance; - } - - init = async () => { - try { - this.scheduler = new Scheduler({ - // storeType: "mongo", - // storeType: "redis", - logLevel: "debug", - debug: true, - // dbUri: this.envSettings.dbConnectionString, - }); - this.scheduler.start(); - - this.scheduler.addTemplate("monitor-job", this.helper.getMonitorJob()); - const monitors = await this.monitorsRepository.findAll(); - for (const monitor of monitors) { - const randomOffset = Math.floor(Math.random() * 100); - setTimeout(() => { - this.addJob(monitor.id, monitor); - }, randomOffset); - } - - return true; - } catch (error) { - this.logger.error({ - message: "Failed to initialize SuperSimpleQueue", - service: SERVICE_NAME, - method: "init", - details: error, - }); - return false; - } - }; - - addJob = async (monitorId, monitor) => { - this.scheduler.addJob({ - id: monitorId, - template: "monitor-job", - repeat: monitor.interval, - active: monitor.isActive, - data: monitor, - }); - }; - - deleteJob = async (monitor) => { - this.scheduler.removeJob(monitor.id); - }; - - pauseJob = async (monitor) => { - const result = this.scheduler.pauseJob(monitor.id); - if (result === false) { - throw new Error("Failed to resume monitor"); - } - this.logger.debug({ - message: `Paused monitor ${monitor.id}`, - service: SERVICE_NAME, - method: "pauseJob", - }); - }; - - resumeJob = async (monitor) => { - const result = this.scheduler.resumeJob(monitor.id); - if (result === false) { - throw new Error("Failed to resume monitor"); - } - this.logger.debug({ - message: `Resumed monitor ${monitor.id}`, - service: SERVICE_NAME, - method: "resumeJob", - }); - }; - - updateJob = async (monitor) => { - this.scheduler.updateJob(monitor.id, { repeat: monitor.interval, data: monitor }); - }; - - shutdown = async () => { - this.scheduler.stop(); - }; - - getMetrics = async () => { - const jobs = await this.scheduler.getJobs(); - const metrics = jobs.reduce( - (acc, job) => { - acc.totalRuns += job.runCount || 0; - acc.totalFailures += job.failCount || 0; - acc.jobs++; - if (job.failCount > 0 && job.lastFailedAt >= job.lsatRunAt) { - acc.failingJobs++; - } - - if (job.lockedAt) { - acc.activeJobs++; - } - - if (job.failCount > 0) { - acc.jobsWithFailures.push({ - monitorId: job.id, - monitorUrl: job?.data?.url || null, - monitorType: job?.data?.type || null, - failedAt: job.lastFailedAt, - failCount: job.failCount, - failReason: job.lastFailReason, - }); - } - return acc; - }, - { - jobs: 0, - activeJobs: 0, - failingJobs: 0, - jobsWithFailures: [], - totalRuns: 0, - totalFailures: 0, - } - ); - return metrics; - }; - - getJobs = async () => { - const jobs = await this.scheduler.getJobs(); - return jobs.map((job) => { - return { - monitorId: job.id, - monitorUrl: job?.data?.url || null, - monitorType: job?.data?.type || null, - monitorInterval: job?.data?.interval || null, - active: job.active, - lockedAt: job.lockedAt, - runCount: job.runCount || 0, - failCount: job.failCount || 0, - failReason: job.lastFailReason, - lastRunAt: job.lastRunAt, - lastFinishedAt: job.lastFinishedAt, - lastRunTook: job.lockedAt ? null : job.lastFinishedAt - job.lastRunAt, - lastFailedAt: job.lastFailedAt, - }; - }); - }; - - flushQueues = async () => { - const stopRes = this.scheduler.stop(); - const flushRes = this.scheduler.flushJobs(); - const initRes = await this.init(); - return { - success: stopRes && flushRes && initRes, - }; - }; - - obliterate = async () => { - console.log("obliterate not implemented"); - }; -} - -export default SuperSimpleQueue; diff --git a/server/src/service/infrastructure/SuperSimpleQueue/SuperSimpleQueue.ts b/server/src/service/infrastructure/SuperSimpleQueue/SuperSimpleQueue.ts new file mode 100644 index 000000000..8fd55ff70 --- /dev/null +++ b/server/src/service/infrastructure/SuperSimpleQueue/SuperSimpleQueue.ts @@ -0,0 +1,254 @@ +import { IMonitorsRepository } from "@/repositories/index.js"; +import Scheduler from "super-simple-scheduler"; +const SERVICE_NAME = "JobQueue"; + +type QueueJobFailure = { + monitorId: string | number; + monitorUrl: string | null; + monitorType: string | null; + failedAt: number | null; + failCount: number; + failReason: string | null; +}; + +type QueueMetrics = { + jobs: number; + activeJobs: number; + failingJobs: number; + jobsWithFailures: QueueJobFailure[]; + totalRuns: number; + totalFailures: number; +}; + +type QueueJobSummary = { + monitorId: string | number; + monitorUrl: string | null; + monitorType: string | null; + monitorInterval: number | null; + active: boolean; + lockedAt: number | null; + runCount: number; + failCount: number; + failReason: string | null; + lastRunAt: number | null; + lastFinishedAt: number | null; + lastRunTook: number | null; + lastFailedAt: number | null; +}; + +export interface ISuperSimpleQueue { + readonly serviceName: string; + init(): Promise; + addJob(monitorId: string, monitor: any): Promise; + deleteJob(monitor: any): Promise; + pauseJob(monitor: any): Promise; + resumeJob(monitor: any): Promise; + updateJob(monitor: any): Promise; + shutdown(): Promise; + getMetrics(): Promise; + getJobs(): Promise; + flushQueues(): Promise<{ success: boolean }>; + obliterate(): Promise; +} + +class SuperSimpleQueue implements ISuperSimpleQueue { + static SERVICE_NAME = SERVICE_NAME; + + private logger: any; + private helper: any; + private monitorsRepository: IMonitorsRepository; + private readonly scheduler: Scheduler; + + constructor({ + logger, + helper, + monitorsRepository, + scheduler, + }: { + logger: any; + helper: any; + monitorsRepository: IMonitorsRepository; + scheduler: Scheduler; + }) { + this.logger = logger; + this.helper = helper; + this.monitorsRepository = monitorsRepository; + this.scheduler = scheduler; + } + + get serviceName() { + return SuperSimpleQueue.SERVICE_NAME; + } + + static async create({ logger, helper, monitorsRepository }: { logger: any; helper: any; monitorsRepository: IMonitorsRepository }) { + const scheduler = new Scheduler({ + // storeType: "mongo", + // storeType: "redis", + logLevel: "debug", + // dbUri: envSettings.dbConnectionString, + }); + const instance = new SuperSimpleQueue({ logger, helper, monitorsRepository, scheduler }); + await instance.init(); + return instance; + } + + init = async () => { + try { + this.scheduler.start(); + + this.scheduler.addTemplate("monitor-job", this.helper.getMonitorJob()); + const monitors = await this.monitorsRepository.findAll(); + if (!monitors) { + return true; + } + for (const monitor of monitors) { + const randomOffset = Math.floor(Math.random() * 100); + setTimeout(() => { + this.addJob(monitor.id, monitor); + }, randomOffset); + } + + return true; + } catch (error) { + this.logger.error({ + message: "Failed to initialize SuperSimpleQueue", + service: SERVICE_NAME, + method: "init", + details: error, + }); + return false; + } + }; + + addJob = async (monitorId: string, monitor: any) => { + this.scheduler.addJob({ + id: monitorId, + template: "monitor-job", + repeat: monitor.interval, + active: monitor.isActive, + data: monitor, + }); + }; + + deleteJob = async (monitor: any) => { + this.scheduler.removeJob(monitor.id); + }; + + pauseJob = async (monitor: any) => { + const result = await this.scheduler.pauseJob(monitor.id); + if (result === false) { + throw new Error("Failed to resume monitor"); + } + this.logger.debug({ + message: `Paused monitor ${monitor.id}`, + service: SERVICE_NAME, + method: "pauseJob", + }); + }; + + resumeJob = async (monitor: any) => { + const result = await this.scheduler.resumeJob(monitor.id); + if (result === false) { + throw new Error("Failed to resume monitor"); + } + this.logger.debug({ + message: `Resumed monitor ${monitor.id}`, + service: SERVICE_NAME, + method: "resumeJob", + }); + }; + + updateJob = async (monitor: any) => { + this.scheduler.updateJob(monitor.id, { repeat: monitor.interval, data: monitor }); + }; + + shutdown = async () => { + this.scheduler.stop(); + }; + + getMetrics = async () => { + const jobs = await this.scheduler.getJobs(); + const metrics = jobs.reduce( + (acc, job) => { + const runCount = job.runCount ?? 0; + const failCount = job.failCount ?? 0; + const lastFailedAt = job.lastFailedAt ?? 0; + const lastRunAt = job.lastRunAt ?? 0; + acc.totalRuns += runCount; + acc.totalFailures += failCount; + acc.jobs++; + if (failCount > 0 && lastFailedAt >= lastRunAt) { + acc.failingJobs++; + } + + if (job.lockedAt) { + acc.activeJobs++; + } + + if (failCount > 0) { + acc.jobsWithFailures.push({ + monitorId: job.id, + monitorUrl: job?.data?.url || null, + monitorType: job?.data?.type || null, + failedAt: job.lastFailedAt ?? null, + failCount, + failReason: job.lastFailReason ?? null, + }); + } + return acc; + }, + { + jobs: 0, + activeJobs: 0, + failingJobs: 0, + jobsWithFailures: [] as Array<{ + monitorId: string | number; + monitorUrl: any; + monitorType: any; + failedAt: number | null; + failCount: number; + failReason: string | null; + }>, + totalRuns: 0, + totalFailures: 0, + } + ); + return metrics; + }; + + getJobs = async () => { + const jobs = await this.scheduler.getJobs(); + return jobs.map((job) => { + return { + monitorId: job.id, + monitorUrl: job?.data?.url || null, + monitorType: job?.data?.type || null, + monitorInterval: job?.data?.interval || null, + active: job.active, + lockedAt: job.lockedAt ?? null, + runCount: job.runCount ?? 0, + failCount: job.failCount ?? 0, + failReason: job.lastFailReason ?? null, + lastRunAt: job.lastRunAt ?? null, + lastFinishedAt: job.lastFinishedAt ?? null, + lastRunTook: job.lockedAt ? null : (job.lastFinishedAt ?? 0) - (job.lastRunAt ?? 0), + lastFailedAt: job.lastFailedAt ?? null, + }; + }); + }; + + flushQueues = async () => { + const stopRes = await this.scheduler.stop(); + const flushRes = await this.scheduler.flushJobs(); + const initRes = await this.init(); + return { + success: Boolean(stopRes && flushRes && initRes), + }; + }; + + obliterate = async () => { + console.log("obliterate not implemented"); + }; +} + +export default SuperSimpleQueue; diff --git a/server/src/service/infrastructure/SuperSimpleQueue/SuperSimpleQueueHelper.js b/server/src/service/infrastructure/SuperSimpleQueue/SuperSimpleQueueHelper.js deleted file mode 100644 index 3cd6b37a8..000000000 --- a/server/src/service/infrastructure/SuperSimpleQueue/SuperSimpleQueueHelper.js +++ /dev/null @@ -1,115 +0,0 @@ -const SERVICE_NAME = "JobQueueHelper"; - -class SuperSimpleQueueHelper { - static SERVICE_NAME = SERVICE_NAME; - - /** - * @param {{ - * db: import("../database.js").Database, - * logger: import("../logger.js").Logger, - * networkService: import("../networkService.js").NetworkService, - * statusService: import("../statusService.js").StatusService, - * notificationService: import("../notificationService.js").NotificationService - * }} - */ - constructor({ db, logger, networkService, statusService, notificationService }) { - this.db = db; - this.logger = logger; - this.networkService = networkService; - this.statusService = statusService; - this.notificationService = notificationService; - } - - get serviceName() { - return SuperSimpleQueueHelper.SERVICE_NAME; - } - - getMonitorJob = () => { - return async (monitor) => { - try { - const monitorId = monitor.id; - const teamId = monitor.teamId; - if (!monitorId) { - throw new Error("No monitor id"); - } - - const maintenanceWindowActive = await this.isInMaintenanceWindow(monitorId, teamId); - if (maintenanceWindowActive) { - this.logger.info({ - message: `Monitor ${monitorId} is in maintenance window`, - service: SERVICE_NAME, - method: "getMonitorJob", - }); - return; - } - const networkResponse = await this.networkService.requestStatus(monitor); - - if (!networkResponse) { - throw new Error("No network response"); - } - - const { monitor: updatedMonitor, statusChanged, prevStatus } = await this.statusService.updateStatus(networkResponse); - - this.notificationService - .handleNotifications({ - ...networkResponse, - monitor: updatedMonitor, - prevStatus, - statusChanged, - }) - .catch((error) => { - this.logger.error({ - message: error.message, - service: SERVICE_NAME, - method: "getMonitorJob", - details: `Error sending notifications for job ${monitor.id}: ${error.message}`, - stack: error.stack, - }); - }); - } catch (error) { - this.logger.warn({ - message: error.message, - service: error.service || SERVICE_NAME, - method: error.method || "getMonitorJob", - stack: error.stack, - }); - throw error; - } - }; - }; - - async isInMaintenanceWindow(monitorId, teamId) { - const maintenanceWindows = await this.db.maintenanceWindowModule.getMaintenanceWindowsByMonitorId({ - monitorId: monitorId.toString(), - teamId: teamId.toString(), - }); - // Check for active maintenance window: - const maintenanceWindowIsActive = maintenanceWindows.reduce((acc, window) => { - if (window.active) { - const start = new Date(window.start); - const end = new Date(window.end); - const now = new Date(); - const repeatInterval = window.repeat || 0; - - // If start is < now and end > now, we're in maintenance - if (start <= now && end >= now) return true; - - // If maintenance window was set in the past with a repeat, - // we need to advance start and end to see if we are in range - - while (start < now && repeatInterval !== 0) { - start.setTime(start.getTime() + repeatInterval); - end.setTime(end.getTime() + repeatInterval); - if (start <= now && end >= now) { - return true; - } - } - return false; - } - return acc; - }, false); - return maintenanceWindowIsActive; - } -} - -export default SuperSimpleQueueHelper; diff --git a/server/src/service/infrastructure/SuperSimpleQueue/SuperSimpleQueueHelper.ts b/server/src/service/infrastructure/SuperSimpleQueue/SuperSimpleQueueHelper.ts new file mode 100644 index 000000000..9a2957ee9 --- /dev/null +++ b/server/src/service/infrastructure/SuperSimpleQueue/SuperSimpleQueueHelper.ts @@ -0,0 +1,158 @@ +const SERVICE_NAME = "JobQueueHelper"; +import type { Monitor } from "@/types/monitor.js"; +import { AppError } from "@/utils/AppError.js"; +import { INetworkService, INotificationsService, IStatusService } from "@/service/index.js"; +import IncidentService from "@/service/business/incidentService.js"; + +class SuperSimpleQueueHelper { + static SERVICE_NAME = SERVICE_NAME; + + private db: any; + private logger: any; + private networkService: INetworkService; + private statusService: IStatusService; + private notificationsService: INotificationsService; + private checkService: any; + private buffer: any; + private incidentService: IncidentService; + + constructor({ + db, + logger, + networkService, + statusService, + notificationsService, + checkService, + buffer, + incidentService, + }: { + db: any; + logger: any; + networkService: INetworkService; + statusService: IStatusService; + notificationsService: INotificationsService; + checkService: any; + buffer: any; + incidentService: IncidentService; + }) { + this.db = db; + this.logger = logger; + this.networkService = networkService; + this.statusService = statusService; + this.checkService = checkService; + this.buffer = buffer; + this.notificationsService = notificationsService; + this.incidentService = incidentService; + } + + get serviceName() { + return SuperSimpleQueueHelper.SERVICE_NAME; + } + + getMonitorJob = () => { + return async (monitor: Monitor) => { + try { + const monitorId = monitor.id; + const teamId = monitor.teamId; + if (!monitorId) { + throw new AppError({ message: "No monitor id", service: SERVICE_NAME, method: "getMonitorJob" }); + } + + // Step 1. Check for maintenacne window, if found, skip the check + const maintenanceWindowActive = await this.isInMaintenanceWindow(monitorId, teamId); + if (maintenanceWindowActive) { + this.logger.debug({ + message: `Monitor ${monitorId} is in maintenance window`, + service: SERVICE_NAME, + method: "getMonitorJob", + }); + return; + } + + // Step 2. Request monitor status + const status = await this.networkService.requestStatus(monitor); + if (!status) { + throw new Error("No network response"); + } + + // Step 3. Build check + const check = await this.checkService.buildCheck(status); + + // Step 4 Add check to buffer + this.buffer.addToBuffer({ check }); + + // Step 4. Update monitor status + const statusChangeResult = await this.statusService.updateMonitorStatus(status, check); + + // Step 5 handle notifications (best effort, continue even in event of failure, don't wait) + this.notificationsService + .handleNotifications(statusChangeResult.monitor, status, statusChangeResult.prevStatus, statusChangeResult.statusChanged) + .catch((error: any) => { + this.logger.error({ + message: error.message, + service: SERVICE_NAME, + method: "getMonitorJob", + details: `Error sending notifications for job ${statusChangeResult.monitor.id}: ${error.message}`, + stack: error.stack, + }); + }); + + // Step 6. Handle incidents (best effort, don't wait) + if (statusChangeResult.statusChanged) { + this.incidentService.handleIncident(statusChangeResult.monitor, statusChangeResult.code).catch((error: any) => { + this.logger.warn({ + message: error.message, + service: SERVICE_NAME, + method: "getMonitorJob", + details: `Error handling incident for job ${monitor.id}: ${error.message}`, + stack: error.stack, + }); + }); + } + } catch (error: any) { + this.logger.warn({ + message: error.message, + service: error.service || SERVICE_NAME, + method: error.method || "getMonitorJob", + stack: error.stack, + }); + throw error; + } + }; + }; + + async isInMaintenanceWindow(monitorId: string, teamId: string) { + const maintenanceWindows = await this.db.maintenanceWindowModule.getMaintenanceWindowsByMonitorId({ + monitorId: monitorId, + teamId: teamId, + }); + // Check for active maintenance window: + const maintenanceWindowIsActive = maintenanceWindows.reduce((acc: any, window: any) => { + if (window.active) { + const start = new Date(window.start); + const end = new Date(window.end); + const now = new Date(); + const repeatInterval = window.repeat || 0; + + // If start is < now and end > now, we're in maintenance + if (start <= now && end >= now) return true; + + // If maintenance window was set in the past with a repeat, + // we need to advance start and end to see if we are in range + + while (start < now && repeatInterval !== 0) { + start.setTime(start.getTime() + repeatInterval); + end.setTime(end.getTime() + repeatInterval); + if (start <= now && end >= now) { + return true; + } + } + return false; + } + return acc; + }, false); + return maintenanceWindowIsActive; + } +} + +export default SuperSimpleQueueHelper; diff --git a/server/src/service/infrastructure/bufferService.js b/server/src/service/infrastructure/bufferService.ts similarity index 51% rename from server/src/service/infrastructure/bufferService.js rename to server/src/service/infrastructure/bufferService.ts index a218f56a0..89cd6a55f 100755 --- a/server/src/service/infrastructure/bufferService.js +++ b/server/src/service/infrastructure/bufferService.ts @@ -1,18 +1,23 @@ import { config } from "@/config/index.js"; +import type { Check } from "@/types/index.js"; const SERVICE_NAME = "BufferService"; class BufferService { static SERVICE_NAME = SERVICE_NAME; - constructor({ db, logger, envSettings, incidentService }) { - console.log(envSettings); + private BUFFER_TIMEOUT: number; + private logger: any; + private SERVICE_NAME: string; + private buffer: any[]; + private bufferTimer: NodeJS.Timeout | null = null; + private checksService: any; + + constructor({ logger, checkService }: { logger: any; checkService: any }) { this.BUFFER_TIMEOUT = config.NODE_ENV === "development" ? 10 : 1000 * 60 * 1; // 1 minute - this.db = db; this.logger = logger; - this.incidentService = incidentService; + this.checksService = checkService; this.SERVICE_NAME = SERVICE_NAME; this.buffer = []; - this.incidentBuffer = []; this.scheduleNextFlush(); this.logger.info({ message: `Buffer service initialized, flushing every ${this.BUFFER_TIMEOUT / 1000}s`, @@ -25,10 +30,10 @@ class BufferService { return BufferService.SERVICE_NAME; } - addToBuffer({ check }) { + addToBuffer({ check }: { check: Check }) { try { this.buffer.push(check); - } catch (error) { + } catch (error: any) { this.logger.error({ message: error.message, service: this.SERVICE_NAME, @@ -38,42 +43,20 @@ class BufferService { } } - addIncidentToBuffer({ monitor, check, action = "create" }) { - try { - if (!monitor || !check) { - this.logger.warn({ - message: "Skipping incident buffer item: missing monitor or check", - service: this.SERVICE_NAME, - method: "addIncidentToBuffer", - }); - return; - } - - this.incidentBuffer.push({ monitor, check, action }); - } catch (error) { - this.logger.error({ - message: error.message, - service: this.SERVICE_NAME, - method: "addIncidentToBuffer", - stack: error.stack, - }); - } - } - - removeCheckFromBuffer(checkToRemove) { + removeCheckFromBuffer(checkToRemove: Check) { try { if (!checkToRemove) { return false; } const index = this.buffer.findIndex((check) => { - if (checkToRemove._id && check._id) { - return check._id.toString() === checkToRemove._id.toString(); + if (checkToRemove.id && check.id) { + return check.id.toString() === checkToRemove.id.toString(); } return ( - check.monitorId?.toString() === checkToRemove.monitorId?.toString() && - check.teamId?.toString() === checkToRemove.teamId?.toString() && - check.type === checkToRemove.type && + check.monitorId?.toString() === checkToRemove.metadata.monitorId && + check.teamId?.toString() === checkToRemove.metadata.teamId && + check.type === checkToRemove.metadata.type && check.status === checkToRemove.status && check.statusCode === checkToRemove.statusCode && check.responseTime === checkToRemove.responseTime && @@ -87,7 +70,7 @@ class BufferService { } return false; - } catch (error) { + } catch (error: any) { this.logger.error({ message: error.message, service: this.SERVICE_NAME, @@ -99,10 +82,13 @@ class BufferService { } scheduleNextFlush() { + if (this.bufferTimer) { + clearTimeout(this.bufferTimer); + } this.bufferTimer = setTimeout(async () => { try { await this.flushBuffer(); - } catch (error) { + } catch (error: any) { this.logger.error({ message: `Error in flush cycle: ${error.message}`, service: this.SERVICE_NAME, @@ -118,22 +104,9 @@ class BufferService { async flushBuffer() { try { if (this.buffer.length > 0) { - await this.db.checkModule.createChecks(this.buffer); + await this.checksService.createChecks(this.buffer); } - } catch (error) { - this.logger.error({ - message: error.message, - service: this.SERVICE_NAME, - method: "flushBuffer", - stack: error.stack, - }); - } - - try { - if (this.incidentBuffer.length > 0 && this.incidentService) { - await this.flushIncidentBuffer(); - } - } catch (error) { + } catch (error: any) { this.logger.error({ message: error.message, service: this.SERVICE_NAME, @@ -143,26 +116,6 @@ class BufferService { } this.buffer = []; - this.incidentBuffer = []; - } - - async flushIncidentBuffer() { - if (!this.incidentService || this.incidentBuffer.length === 0) { - return; - } - - try { - const itemsToProcess = [...this.incidentBuffer]; - await this.incidentService.processIncidentsFromBuffer(itemsToProcess); - } catch (error) { - this.logger.error({ - message: `Error flushing incident buffer: ${error.message}`, - service: this.SERVICE_NAME, - method: "flushIncidentBuffer", - stack: error.stack, - }); - throw error; - } } } diff --git a/server/src/service/infrastructure/emailService.js b/server/src/service/infrastructure/emailService.ts similarity index 67% rename from server/src/service/infrastructure/emailService.js rename to server/src/service/infrastructure/emailService.ts index ed661ff16..8598f112f 100755 --- a/server/src/service/infrastructure/emailService.js +++ b/server/src/service/infrastructure/emailService.ts @@ -1,28 +1,27 @@ import { fileURLToPath } from "url"; import path from "path"; +import { EmailTransportConfig } from "@/types/index.js"; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const SERVICE_NAME = "EmailService"; -/** - * Represents an email service that can load templates, build, and send emails. - */ class EmailService { static SERVICE_NAME = SERVICE_NAME; - /** - * Constructs an instance of the EmailService, initializing template loaders and the email transporter. - * @param {Object} settingsService - The settings service to get email configuration. - * @param {Object} fs - The file system module. - * @param {Object} path - The path module. - * @param {Function} compile - The Handlebars compile function. - * @param {Function} mjml2html - The MJML to HTML conversion function. - * @param {Object} nodemailer - The nodemailer module. - * @param {Object} logger - The logger module. - */ - constructor(settingsService, fs, path, compile, mjml2html, nodemailer, logger) { + private settingsService: any; + private fs: any; + private path: any; + private compile: any; + private mjml2html: any; + private nodemailer: any; + private logger: any; + private transporter: any; + private templateLookup: Record; + private loadTemplate: (templateName: string) => Function; + + constructor(settingsService: any, fs: any, path: any, compile: any, mjml2html: any, nodemailer: any, logger: any) { this.settingsService = settingsService; this.fs = fs; this.path = path; @@ -31,6 +30,10 @@ class EmailService { this.nodemailer = nodemailer; this.logger = logger; this.init(); + this.templateLookup = {}; + this.loadTemplate = () => { + return () => {}; + }; } get serviceName() { @@ -38,18 +41,12 @@ class EmailService { } init = async () => { - /** - * Loads an email template from the filesystem. - * - * @param {string} templateName - The name of the template to load. - * @returns {Function} A compiled template function that can be used to generate HTML email content. - */ this.loadTemplate = (templateName) => { try { - const templatePath = this.path.join(__dirname, `../../../templates/${templateName}.mjml`); + const templatePath = this.path.join(__dirname, `../../templates/${templateName}.mjml`); const templateContent = this.fs.readFileSync(templatePath, "utf8"); return this.compile(templateContent); - } catch (error) { + } catch (error: any) { this.logger.error({ message: error.message, service: SERVICE_NAME, @@ -59,11 +56,6 @@ class EmailService { } }; - /** - * A lookup object to access preloaded email templates. - * @type {Object.} - * TODO Load less used templates in their respective functions - */ this.templateLookup = { welcomeEmailTemplate: this.loadTemplate("welcomeEmail"), employeeActivationTemplate: this.loadTemplate("employeeActivation"), @@ -74,19 +66,14 @@ class EmailService { hardwareIncidentTemplate: this.loadTemplate("hardwareIncident"), testEmailTemplate: this.loadTemplate("testEmailTemplate"), }; - - /** - * The email transporter used to send emails. - * @type {Object} - */ }; - buildEmail = async (template, context) => { + buildEmail = async (template: string, context: Record) => { try { - const mjml = this.templateLookup[template](context); + const mjml = this.templateLookup[template]?.(context); const html = await this.mjml2html(mjml); return html.html; - } catch (error) { + } catch (error: any) { this.logger.error({ message: error.message, service: SERVICE_NAME, @@ -96,8 +83,8 @@ class EmailService { } }; - sendEmail = async (to, subject, html, transportConfig) => { - let config; + sendEmail = async (to: string, subject: string, html: string, transportConfig?: EmailTransportConfig) => { + let config: EmailTransportConfig; if (typeof transportConfig !== "undefined") { config = transportConfig; } else { @@ -157,7 +144,7 @@ class EmailService { html: html, }); return info?.messageId; - } catch (error) { + } catch (error: any) { this.logger.error({ message: error.message, service: SERVICE_NAME, diff --git a/server/src/service/infrastructure/networkService.js b/server/src/service/infrastructure/networkService.ts similarity index 65% rename from server/src/service/infrastructure/networkService.js rename to server/src/service/infrastructure/networkService.ts index 2375e7233..e4e5972af 100644 --- a/server/src/service/infrastructure/networkService.js +++ b/server/src/service/infrastructure/networkService.ts @@ -1,10 +1,145 @@ +import { HTTPError, RequestError } from "got"; +import type { Got, Response } from "got"; +import type { Monitor, MonitorStatusResponse } from "@/types/index.js"; + import CacheableLookup from "cacheable-lookup"; const SERVICE_NAME = "NetworkService"; -class NetworkService { +type MonitorStatusResponseOverrides = Partial, "monitorId" | "teamId" | "type">>; + +interface BuildStatusResponseArgs { + monitor: Monitor; + response?: Response | null; + error?: Error | RequestError | HTTPError | null; + payload?: T | null; + jsonPath?: string; + matchMethod?: MonitorStatusResponse["matchMethod"]; + expectedValue?: string; + extracted?: unknown; + overrides?: MonitorStatusResponseOverrides; +} + +export interface INetworkService { + readonly serviceName: string; + requestStatus(monitor: Monitor): Promise; + requestWebhook(type: string, url: string, body: any): Promise<{ type: string; status: boolean; code: number; message: string; payload?: unknown }>; + requestPagerDuty(args: { message: string; routingKey: string; monitorUrl: string }): Promise; + requestMatrix(args: { homeserverUrl: string; accessToken: string; roomId: string; message: string }): Promise<{ + status: boolean; + code: number; + message: string; + payload?: unknown; + }>; +} + +class NetworkService implements INetworkService { static SERVICE_NAME = SERVICE_NAME; - constructor({ axios, got, https, jmespath, GameDig, ping, logger, http, Docker, net, stringService, settingsService }) { + private TYPE_PING: string; + private TYPE_HTTP: string; + private TYPE_PAGESPEED: string; + private TYPE_HARDWARE: string; + private TYPE_DOCKER: string; + private TYPE_PORT: string; + private TYPE_GAME: string; + private SERVICE_NAME: string; + private NETWORK_ERROR: number; + private PING_ERROR: number; + + private axios: any; + private got: Got; + private https: any; + private jmespath: any; + private GameDig: any; + private ping: any; + private logger: any; + private http: any; + private Docker: any; + private net: any; + private stringService: any; + private settingsService: any; + + private buildStatusResponse = ({ + monitor, + response, + error, + payload, + jsonPath, + matchMethod, + expectedValue, + extracted, + overrides, + }: BuildStatusResponseArgs): MonitorStatusResponse => { + if (error) { + const statusResponse: MonitorStatusResponse = { + monitorId: monitor.id, + teamId: monitor.teamId, + type: monitor.type, + status: false, + code: this.NETWORK_ERROR, + message: error.message ?? "Network error", + responseTime: 0, + timings: undefined, + jsonPath, + matchMethod, + expectedValue, + extracted, + payload, + }; + if (error instanceof HTTPError || error instanceof RequestError) { + statusResponse.code = error?.response?.statusCode ?? this.NETWORK_ERROR; + statusResponse.message = error.message; + statusResponse.responseTime = error.timings?.phases?.total ?? 0; + statusResponse.timings = error.timings; + } + return { ...statusResponse, ...(overrides ?? {}) }; + } + + return { + monitorId: monitor.id, + teamId: monitor.teamId, + type: monitor.type, + status: response?.ok ?? false, + code: response?.statusCode ?? this.NETWORK_ERROR, + message: response?.statusMessage ?? "", + responseTime: response?.timings?.phases?.total ?? 0, + timings: response?.timings, + payload: payload ?? response?.body, + jsonPath, + matchMethod, + expectedValue, + extracted, + ...(overrides ?? {}), + }; + }; + + constructor({ + axios, + got, + https, + jmespath, + GameDig, + ping, + logger, + http, + Docker, + net, + stringService, + settingsService, + }: { + axios: any; + got: Got; + https: any; + jmespath: any; + GameDig: any; + ping: any; + logger: any; + http: any; + Docker: any; + net: any; + stringService: any; + settingsService: any; + }) { this.TYPE_PING = "ping"; this.TYPE_HTTP = "http"; this.TYPE_PAGESPEED = "pagespeed"; @@ -17,11 +152,11 @@ class NetworkService { this.PING_ERROR = 5001; this.axios = axios; this.https = https; + this.http = http; this.jmespath = jmespath; this.GameDig = GameDig; this.ping = ping; this.logger = logger; - this.http = http; this.Docker = Docker; this.net = net; this.stringService = stringService; @@ -38,13 +173,17 @@ class NetworkService { }); } + get serviceName(): string { + return NetworkService.SERVICE_NAME; + } + // Helper functions - async timeRequest(operation) { + private async timeRequest(operation: () => Promise): Promise<{ response: T | null; responseTime: number; error: unknown }> { const start = process.hrtime.bigint(); try { const response = await operation(); const elapsedMs = Math.round(Number(process.hrtime.bigint() - start) / 1_000_000); - return { response, responseTime: elapsedMs }; + return { response, responseTime: elapsedMs, error: null }; } catch (error) { const elapsedMs = Math.round(Number(process.hrtime.bigint() - start) / 1_000_000); return { response: null, responseTime: elapsedMs, error }; @@ -52,7 +191,7 @@ class NetworkService { } // Main entry point - async requestStatus(monitor) { + async requestStatus(monitor: Monitor): Promise { const type = monitor?.type || "unknown"; switch (type) { case this.TYPE_PING: @@ -70,11 +209,11 @@ class NetworkService { case this.TYPE_GAME: return await this.requestGame(monitor); default: - return await this.handleUnsupportedType(type); + return this.handleUnsupportedType(type); } } - async requestPing(monitor) { + private async requestPing(monitor: Monitor): Promise { try { if (!monitor?.url) { throw new Error("Monitor URL is required"); @@ -94,44 +233,49 @@ class NetworkService { throw new Error("Ping failed - no result returned"); } - const pingResponse = { - monitorId: monitor.id, - type: "ping", - status: response.alive, - code: 200, - responseTime: response.time, - message: "Success", + const pingResponse = this.buildStatusResponse({ + monitor, payload: response, - }; + overrides: { + status: (response as { alive?: boolean })?.alive ?? false, + code: 200, + message: "Success", + responseTime: (response as { time?: number })?.time ?? 0, + payload: response, + }, + }); if (error) { pingResponse.status = false; - pingResponse.code = 200; + pingResponse.code = this.PING_ERROR; pingResponse.message = "Ping failed"; return pingResponse; } return pingResponse; - } catch (err) { + } catch (err: any) { err.service = this.SERVICE_NAME; err.method = "requestPing"; throw err; } } - async requestHttp(monitor) { + private async requestHttp(monitor: Monitor): Promise { const { url, secret, id, teamId, type, ignoreTlsErrors, jsonPath, matchMethod, expectedValue } = monitor; - const httpResponse = { - monitorId: id, - teamId: teamId, - type, - }; + const httpResponse = this.buildStatusResponse({ + monitor, + overrides: { + status: false, + code: this.NETWORK_ERROR, + message: "Request not executed", + }, + }); try { if (!url) { throw new Error("Monitor URL is required"); } - const config = { + const config: Record = { headers: secret ? { Authorization: `Bearer ${secret}` } : undefined, }; @@ -145,7 +289,7 @@ class NetworkService { const response = await this.got(url, config); - let payload; + let payload: any; const contentType = response.headers["content-type"]; if (contentType && contentType.includes("application/json")) { @@ -158,12 +302,14 @@ class NetworkService { payload = response.body; } - httpResponse.code = response.statusCode; - httpResponse.status = response.ok; - httpResponse.message = response.statusMessage; - httpResponse.responseTime = response.timings.phases.total || 0; - httpResponse.payload = payload; - httpResponse.timings = response.timings || {}; + Object.assign(httpResponse, { + code: response.statusCode, + status: response.ok, + message: response.statusMessage ?? "", + responseTime: response.timings.phases.total || 0, + payload, + timings: response.timings, + }); if (!expectedValue && !jsonPath) { return httpResponse; @@ -231,7 +377,7 @@ class NetworkService { } } return httpResponse; - } catch (err) { + } catch (err: any) { if (err.name === "HTTPError" || err.name === "RequestError") { httpResponse.code = err?.response?.statusCode || this.NETWORK_ERROR; httpResponse.status = false; @@ -247,7 +393,7 @@ class NetworkService { } } - async requestPageSpeed(monitor) { + private async requestPageSpeed(monitor: Monitor): Promise { try { const url = monitor.url; if (!url) { @@ -269,24 +415,24 @@ class NetworkService { ...monitor, url: pageSpeedUrl, }); - } catch (err) { + } catch (err: any) { err.service = this.SERVICE_NAME; err.method = "requestPageSpeed"; throw err; } } - async requestHardware(monitor) { + private async requestHardware(monitor: Monitor): Promise { try { return await this.requestHttp(monitor); - } catch (err) { + } catch (err: any) { err.service = this.SERVICE_NAME; err.method = "requestHardware"; throw err; } } - async requestDocker(monitor) { + private async requestDocker(monitor: Monitor): Promise { try { if (!monitor.url) { throw new Error("Monitor URL is required"); @@ -297,10 +443,14 @@ class NetworkService { handleError: true, // Enable error handling }); - const dockerResponse = { - monitorId: monitor.id, - type: monitor.type, - }; + const dockerResponse = this.buildStatusResponse({ + monitor, + overrides: { + status: false, + code: this.NETWORK_ERROR, + message: "No response", + }, + }); const containers = await docker.listContainers({ all: true }); @@ -309,18 +459,18 @@ class NetworkService { // Priority-based matching to avoid ambiguity: // 1. Exact full ID match (64-char) - let exactIdMatch = containers.find((c) => c.Id.toLowerCase() === normalizedInput); + let exactIdMatch = containers.find((c: any) => c.Id.toLowerCase() === normalizedInput); // 2. Exact container name match (case-insensitive) - let exactNameMatch = containers.find((c) => - c.Names.some((name) => { + let exactNameMatch = containers.find((c: any) => + c.Names.some((name: string) => { const cleanName = name.replace(/^\/+/, "").toLowerCase(); return cleanName === normalizedInput; }) ); // 3. Partial ID match (fallback for backwards compatibility) - let partialIdMatch = containers.find((c) => c.Id.toLowerCase().startsWith(normalizedInput)); + let partialIdMatch = containers.find((c: any) => c.Id.toLowerCase().startsWith(normalizedInput)); // Select container based on priority let targetContainer = exactIdMatch || exactNameMatch || partialIdMatch; @@ -353,14 +503,15 @@ class NetworkService { method: "requestDocker", details: { url: monitor.url }, }); - dockerResponse.status = 404; dockerResponse.status = false; dockerResponse.message = `Ambiguous container match for "${monitor.url}". Matched by: ${matchTypes.join(", ")}. Using ${exactIdMatch ? "exact ID" : exactNameMatch ? "exact name" : "partial ID"} match.`; return dockerResponse; } const container = docker.getContainer(targetContainer.Id); - const { response, responseTime, error } = await this.timeRequest(() => container.inspect()); + const { response, responseTime, error }: { response?: any; responseTime?: number; error?: any } = await this.timeRequest(() => + container.inspect() + ); dockerResponse.responseTime = responseTime; dockerResponse.status = response?.State?.Status === "running" ? true : false; @@ -375,14 +526,14 @@ class NetworkService { } return dockerResponse; - } catch (err) { + } catch (err: any) { err.service = this.SERVICE_NAME; err.method = "requestDocker"; throw err; } } - async requestPort(monitor) { + private async requestPort(monitor: Monitor): Promise { try { const { url, port } = monitor; const { response, responseTime, error } = await this.timeRequest(async () => { @@ -405,21 +556,22 @@ class NetworkService { reject(new Error("Connection timeout")); }); - socket.on("error", (err) => { + socket.on("error", (err: any) => { socket.destroy(); reject(err); }); }); }); - const portResponse = { - code: 200, - status: response.success, - message: this.stringService.portSuccess, - monitorId: monitor.id, - type: monitor.type, - responseTime: responseTime, - }; + const portResponse = this.buildStatusResponse({ + monitor, + overrides: { + code: 200, + status: (response as { success?: boolean })?.success ?? false, + message: this.stringService.portSuccess, + responseTime, + }, + }); if (error) { portResponse.code = this.NETWORK_ERROR; @@ -429,30 +581,31 @@ class NetworkService { } return portResponse; - } catch (error) { + } catch (error: any) { error.service = this.SERVICE_NAME; error.method = "requestTCP"; throw error; } } - async requestGame(monitor) { + private async requestGame(monitor: Monitor): Promise { try { const { url, port, gameId } = monitor; - const gameResponse = { - code: 200, - status: true, - message: "Success", - monitorId: monitor.id, - type: "game", - }; + const gameResponse = this.buildStatusResponse({ + monitor, + overrides: { + code: 200, + status: true, + message: "Success", + }, + }); const state = await this.GameDig.query({ type: gameId, host: url, port: port, - }).catch((error) => { + }).catch((error: any) => { this.logger.warn({ message: error.message, service: this.SERVICE_NAME, @@ -471,21 +624,25 @@ class NetworkService { gameResponse.responseTime = state.ping; gameResponse.payload = state; return gameResponse; - } catch (error) { + } catch (error: any) { error.service = this.SERVICE_NAME; error.method = "requestPing"; throw error; } } - async handleUnsupportedType(type) { - const err = new Error(`Unsupported type: ${type}`); - err.service = this.SERVICE_NAME; - err.method = "getStatus"; - throw err; + private async handleUnsupportedType(type: string): Promise { + return { + monitorId: "unknown", + teamId: "unknown", + type: "unknown", + status: false, + code: this.NETWORK_ERROR, + message: `Unsupported type: ${type}`, + }; } // Other network requests unrelated to monitoring: - async requestWebhook(type, url, body) { + async requestWebhook(type: string, url: string, body: any) { try { const response = await this.axios.post(url, body, { headers: { @@ -500,7 +657,7 @@ class NetworkService { message: `Successfully sent ${type} notification`, payload: response.data, }; - } catch (error) { + } catch (error: any) { this.logger.warn({ message: error.message, service: this.SERVICE_NAME, @@ -517,7 +674,7 @@ class NetworkService { } } - async requestPagerDuty({ message, routingKey, monitorUrl }) { + async requestPagerDuty({ message, routingKey, monitorUrl }: { message: string; routingKey: string; monitorUrl: string }) { try { const response = await this.axios.post(`https://events.pagerduty.com/v2/enqueue`, { routing_key: routingKey, @@ -532,7 +689,7 @@ class NetworkService { if (response?.data?.status !== "success") return false; return true; - } catch (error) { + } catch (error: any) { error.details = error.response?.data; error.service = this.SERVICE_NAME; error.method = "requestPagerDuty"; @@ -540,7 +697,17 @@ class NetworkService { } } - async requestMatrix({ homeserverUrl, accessToken, roomId, message }) { + async requestMatrix({ + homeserverUrl, + accessToken, + roomId, + message, + }: { + homeserverUrl: string; + accessToken: string; + roomId: string; + message: string; + }) { try { const url = `${homeserverUrl}/_matrix/client/v3/rooms/${roomId}/send/m.room.message?access_token=${accessToken}`; const body = { @@ -560,7 +727,7 @@ class NetworkService { code: response.status, message: "Successfully sent Matrix notification", }; - } catch (error) { + } catch (error: any) { this.logger.warn({ message: error.message, service: this.SERVICE_NAME, diff --git a/server/src/service/infrastructure/notificationProviders/INotificationProvider.ts b/server/src/service/infrastructure/notificationProviders/INotificationProvider.ts new file mode 100644 index 000000000..2d363d6b3 --- /dev/null +++ b/server/src/service/infrastructure/notificationProviders/INotificationProvider.ts @@ -0,0 +1,6 @@ +import type { Monitor, Notification, Alert, MonitorStatusResponse } from "@/types/index.js"; + +export interface INotificationProvider { + sendAlert: (notification: Notification, monitor: Monitor, monitorStatusResponse: MonitorStatusResponse) => Promise; + sendTestAlert(notification: Notification): Promise; +} diff --git a/server/src/service/infrastructure/notificationProviders/discord.ts b/server/src/service/infrastructure/notificationProviders/discord.ts new file mode 100644 index 000000000..ad1f2f28a --- /dev/null +++ b/server/src/service/infrastructure/notificationProviders/discord.ts @@ -0,0 +1,72 @@ +const SERVICE_NAME = "DiscordProvider"; +import type { Monitor, Notification, MonitorStatusResponse } from "@/types/index.js"; +import { INotificationProvider } from "@/service/index.js"; +import { buildHardwareAlerts, buildDiscordBody, getTestMessage } from "@/service/infrastructure/notificationProviders/utils.js"; +import got from "got"; + +export class DiscordProvider implements INotificationProvider { + private logger: any; + + constructor(logger: any) { + this.logger = logger; + } + private getHardwareContent = (monitor: Monitor, monitorStatusResponse: MonitorStatusResponse) => { + const { discordPayload } = buildHardwareAlerts("HOST_PLACEHOLDER", monitor, monitorStatusResponse); + return discordPayload; + }; + + sendAlert = async (notification: Notification, monitor: Monitor, monitorStatusResponse: MonitorStatusResponse) => { + let body; + if (monitor.type === "hardware") { + body = this.getHardwareContent(monitor, monitorStatusResponse); + } else { + body = buildDiscordBody(monitor, monitorStatusResponse); + } + + if (!notification.address) { + return false; + } + + try { + await got.post(notification.address, { + json: body, + headers: { + "Content-Type": "application/json", + }, + }); + return true; + } catch (error) { + const err = error as Error; + this.logger.warn({ + message: "Discord alert failed", + service: SERVICE_NAME, + method: "sendAlert", + stack: err?.stack, + }); + return false; + } + }; + sendTestAlert = async (notification: Notification) => { + if (!notification.address) { + return false; + } + try { + await got.post(notification.address, { + json: { content: getTestMessage() }, + headers: { + "Content-Type": "application/json", + }, + }); + return true; + } catch (error) { + const err = error as Error; + this.logger.warn({ + message: "Discord test alert failed", + service: SERVICE_NAME, + method: "sendTestAlert", + stack: err?.stack, + }); + return false; + } + }; +} diff --git a/server/src/service/infrastructure/notificationProviders/email.ts b/server/src/service/infrastructure/notificationProviders/email.ts new file mode 100644 index 000000000..16e48f5c1 --- /dev/null +++ b/server/src/service/infrastructure/notificationProviders/email.ts @@ -0,0 +1,61 @@ +const SERVICE_NAME = "EmailProvider"; +import type { Monitor, Notification, MonitorStatusResponse } from "@/types/index.js"; +import { INotificationProvider } from "@/service/index.js"; +import { buildHardwareAlerts, buildHardwareEmail, buildEmail, buildTestEmail } from "@/service/infrastructure/notificationProviders/utils.js"; + +export class EmailProvider implements INotificationProvider { + private emailService: any; + private logger: any; + + constructor(emailService: any, logger: any) { + this.emailService = emailService; + this.logger = logger; + } + + private buildHardwareEmail = (monitor: Monitor, monitorStatusResponse: MonitorStatusResponse) => { + const { alertsToSend } = buildHardwareAlerts("HOST_PLACEHOLDER", monitor, monitorStatusResponse); + const html = buildHardwareEmail(this.emailService, monitor, alertsToSend); + return html; + }; + + async sendAlert(notification: Notification, monitor: Monitor, monitorStatusResponse: MonitorStatusResponse): Promise { + const subject = `Monitor ${monitor.name} infrastructure alerts`; + let html; + if (monitor.type === "hardware") { + html = this.buildHardwareEmail(monitor, monitorStatusResponse); + } else { + html = await buildEmail(this.emailService, monitor); + } + + if (!notification.address) { + return false; + } + + const messageId = await this.emailService.sendEmail(notification.address, subject, html); + if (!messageId) { + this.logger.warn({ + message: "Email alert failed", + service: SERVICE_NAME, + method: "sendAlert", + }); + return false; + } + return true; + } + + async sendTestAlert(notification: Notification): Promise { + const subject = "Test notification"; + const html = await buildTestEmail(this.emailService); + + const messageId = await this.emailService.sendEmail(notification.address, subject, html); + if (!messageId) { + this.logger.warn({ + message: "Email test alert failed", + service: SERVICE_NAME, + method: "sendTestAlert", + }); + return false; + } + return true; + } +} diff --git a/server/src/service/infrastructure/notificationProviders/matrix.js b/server/src/service/infrastructure/notificationProviders/matrix.js deleted file mode 100644 index a8b33d4b8..000000000 --- a/server/src/service/infrastructure/notificationProviders/matrix.js +++ /dev/null @@ -1,34 +0,0 @@ -const SERVICE_NAME = "Matrix"; - -class Matrix { - static SERVICE_NAME = SERVICE_NAME; - - constructor({ networkService, logger }) { - this.networkService = networkService; - this.logger = logger; - } - - get serviceName() { - return Matrix.SERVICE_NAME; - } - - async send({ friendlyName, homeserverUrl, accessToken, roomId, message, monitorName }) { - const title = `Checkmate status for ${monitorName}`; - const formattedMessage = `## ${title}\n${message}`; - try { - await this.networkService.requestMatrix({ - homeserverUrl, - accessToken, - roomId, - message: formattedMessage, - }); - this.logger.info(`Successfully sent Matrix notification for ${friendlyName}`); - return true; - } catch (error) { - this.logger.error(`Failed to send Matrix notification for ${friendlyName}: ${error.message}`); - return false; - } - } -} - -export default Matrix; diff --git a/server/src/service/infrastructure/notificationProviders/matrix.ts b/server/src/service/infrastructure/notificationProviders/matrix.ts new file mode 100644 index 000000000..8914dbf80 --- /dev/null +++ b/server/src/service/infrastructure/notificationProviders/matrix.ts @@ -0,0 +1,99 @@ +const SERVICE_NAME = "MatrixProvider"; +import got from "got"; +import type { INotificationProvider } from "@/service/index.js"; +import type { Notification, Monitor, MonitorStatusResponse } from "@/types/index.js"; +import { + buildHardwareAlerts, + buildHardwareWebhookBody, + buildWebhookBody, + getTestMessage, +} from "@/service/infrastructure/notificationProviders/utils.js"; + +export class MatrixProvider implements INotificationProvider { + private logger: any; + + constructor(logger: any) { + this.logger = logger; + } + private getHardwareContent = (monitor: Monitor, monitorStatusResponse: MonitorStatusResponse) => { + const { alertsToSend } = buildHardwareAlerts("HOST_PLACEHOLDER", monitor, monitorStatusResponse); + const body = buildHardwareWebhookBody(alertsToSend, monitor); + return body; + }; + + private getContent = (monitor: Monitor, monitorStatusResponse: MonitorStatusResponse) => { + const body = buildWebhookBody(monitor, monitorStatusResponse); + return body; + }; + + sendAlert = async (notification: Notification, monitor: Monitor, monitorStatusResponse: MonitorStatusResponse) => { + const { homeserverUrl, accessToken, roomId } = notification; + + let content; + if (monitor.type === "hardware") { + content = this.getHardwareContent(monitor, monitorStatusResponse); + } else { + content = this.getContent(monitor, monitorStatusResponse); + } + + const title = `Checkmate status for ${monitor.name}`; + + const formattedMessage = `## ${title}\n${content}`; + + const url = `${homeserverUrl}/_matrix/client/v3/rooms/${roomId}/send/m.room.message?access_token=${accessToken}`; + const body = { + msgtype: "m.text", + body: formattedMessage, + format: "org.matrix.custom.html", + formatted_body: formattedMessage, + }; + try { + await got.post(url, { + json: body, + headers: { + "Content-Type": "application/json", + }, + }); + return true; + } catch (error) { + const err = error as Error; + this.logger.warn({ + message: "Matrix alert failed", + service: SERVICE_NAME, + method: "sendAlert", + stack: err?.stack, + }); + return false; + } + }; + + sendTestAlert = async (notification: Notification) => { + const { homeserverUrl, accessToken, roomId } = notification; + if (!homeserverUrl || !accessToken || !roomId) { + return false; + } + const url = `${homeserverUrl}/_matrix/client/v3/rooms/${roomId}/send/m.room.message?access_token=${accessToken}`; + const body = { + msgtype: "m.text", + body: getTestMessage(), + }; + try { + await got.post(url, { + json: body, + headers: { + "Content-Type": "application/json", + }, + }); + return true; + } catch (error) { + const err = error as Error; + this.logger.warn({ + message: "Matrix test alert failed", + service: SERVICE_NAME, + method: "sendTestAlert", + stack: err?.stack, + }); + return false; + } + }; +} diff --git a/server/src/service/infrastructure/notificationProviders/pagerduty.ts b/server/src/service/infrastructure/notificationProviders/pagerduty.ts new file mode 100644 index 000000000..f65e50c68 --- /dev/null +++ b/server/src/service/infrastructure/notificationProviders/pagerduty.ts @@ -0,0 +1,91 @@ +const SERVICE_NAME = "PagerDutyProvider"; +import got from "got"; +import type { Monitor, Notification, MonitorStatusResponse } from "@/types/index.js"; +import { INotificationProvider } from "@/service/index.js"; +import { + buildHardwareAlerts, + buildHardwareWebhookBody, + buildWebhookBody, + getTestMessage, +} from "@/service/infrastructure/notificationProviders/utils.js"; + +export class PagerDutyProvider implements INotificationProvider { + private logger: any; + + constructor(logger: any) { + this.logger = logger; + } + private getHardwareContent = (monitor: Monitor, monitorStatusResponse: MonitorStatusResponse) => { + const { alertsToSend } = buildHardwareAlerts("HOST_PLACEHOLDER", monitor, monitorStatusResponse); + const body = buildHardwareWebhookBody(alertsToSend, monitor); + return body; + }; + + private getContent = (monitor: Monitor, monitorStatusResponse: MonitorStatusResponse) => { + const body = buildWebhookBody(monitor, monitorStatusResponse); + return body; + }; + + async sendAlert(notification: Notification, monitor: Monitor, monitorStatusResponse: MonitorStatusResponse): Promise { + let body; + if (monitor.type === "hardware") { + body = this.getHardwareContent(monitor, monitorStatusResponse); + } else { + body = this.getContent(monitor, monitorStatusResponse); + } + + try { + await got.post("https://events.pagerduty.com/v2/enqueue", { + json: { + routing_key: notification.address, + event_action: "trigger", + payload: { + summary: body, + severity: "critical", + source: monitor.url, + timestamp: new Date().toISOString(), + }, + }, + }); + + return true; + } catch (error) { + const err = error as Error; + this.logger.warn({ + message: "PagerDuty alert failed", + service: SERVICE_NAME, + method: "sendAlert", + stack: err?.stack, + }); + return false; + } + } + + async sendTestAlert(notification: Notification): Promise { + try { + await got.post("https://events.pagerduty.com/v2/enqueue", { + json: { + routing_key: notification.address, + event_action: "trigger", + payload: { + summary: getTestMessage(), + severity: "info", + source: "checkmate", + timestamp: new Date().toISOString(), + }, + }, + responseType: "json", + }); + return true; + } catch (error) { + const err = error as Error; + this.logger.warn({ + message: "PagerDuty test alert failed", + service: SERVICE_NAME, + method: "sendTestAlert", + stack: err?.stack, + }); + return false; + } + } +} diff --git a/server/src/service/infrastructure/notificationProviders/slack.ts b/server/src/service/infrastructure/notificationProviders/slack.ts new file mode 100644 index 000000000..2aeb442eb --- /dev/null +++ b/server/src/service/infrastructure/notificationProviders/slack.ts @@ -0,0 +1,85 @@ +const SERVICE_NAME = "SlackProvider"; +import type { Monitor, Notification, MonitorStatusResponse } from "@/types/index.js"; +import { INotificationProvider } from "@/service/index.js"; +import { + buildHardwareAlerts, + buildHardwareWebhookBody, + buildWebhookBody, + getTestMessage, +} from "@/service/infrastructure/notificationProviders/utils.js"; +import got, { HTTPError } from "got"; + +export class SlackProvider implements INotificationProvider { + private logger: any; + + constructor(logger: any) { + this.logger = logger; + } + private getHardwareContent = (monitor: Monitor, monitorStatusResponse: MonitorStatusResponse) => { + const { alertsToSend } = buildHardwareAlerts("HOST_PLACEHOLDER", monitor, monitorStatusResponse); + const body = buildHardwareWebhookBody(alertsToSend, monitor); + return body; + }; + + private getContent = (monitor: Monitor, monitorStatusResponse: MonitorStatusResponse) => { + const body = buildWebhookBody(monitor, monitorStatusResponse); + return body; + }; + + async sendAlert(notification: Notification, monitor: Monitor, monitorStatusResponse: MonitorStatusResponse): Promise { + let body; + if (monitor.type === "hardware") { + body = this.getHardwareContent(monitor, monitorStatusResponse); + } else { + body = this.getContent(monitor, monitorStatusResponse); + } + + if (!notification.address) { + return false; + } + + try { + await got.post(notification.address, { + json: { text: body }, + headers: { + "Content-Type": "application/json", + }, + }); + return true; + } catch (error) { + const err = error as Error; + this.logger.warn({ + message: "Slack alert failed", + service: SERVICE_NAME, + method: "sendAlert", + stack: err?.stack, + }); + return false; + } + } + + async sendTestAlert(notification: Notification): Promise { + if (!notification.address) { + return false; + } + + try { + await got.post(notification.address, { + json: { text: getTestMessage() }, + headers: { + "Content-Type": "application/json", + }, + }); + return true; + } catch (error) { + const err = error as HTTPError; + this.logger.warn({ + message: "Slack test alert failed", + service: SERVICE_NAME, + method: "sendTestAlert", + stack: err?.stack, + }); + return false; + } + } +} diff --git a/server/src/service/infrastructure/notificationProviders/utils.ts b/server/src/service/infrastructure/notificationProviders/utils.ts new file mode 100644 index 000000000..f71933425 --- /dev/null +++ b/server/src/service/infrastructure/notificationProviders/utils.ts @@ -0,0 +1,202 @@ +import { Monitor, HardwareStatusPayload, MonitorStatusResponse } from "@/types/index.js"; + +const getTime = (): { localTimeZone: string; localTime: string; utcTime: string } => { + const now = new Date(); + const localTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone; + const localTime = new Intl.DateTimeFormat(undefined, { + year: "numeric", + month: "2-digit", + day: "2-digit", + hour: "2-digit", + minute: "2-digit", + second: "2-digit", + hour12: false, + timeZone: localTimeZone, + timeZoneName: "short", + }).format(now); + const utcTime = now.toUTCString(); + return { localTimeZone, localTime, utcTime }; +}; + +export const buildHardwareAlerts = ( + clientHost: string, + monitor: Monitor, + networkResponse: MonitorStatusResponse +): { alertsToSend: string[]; discordPayload: any } => { + const thresholds = monitor.thresholds || {}; + const { usage_cpu: cpuThreshold = -1, usage_memory: memoryThreshold = -1, usage_disk: diskThreshold = -1 } = thresholds; + + const payload = networkResponse?.payload as HardwareStatusPayload; + const metrics = payload.data || {}; + const { cpu: { usage_percent: cpuUsage = -1 } = {}, memory: { usage_percent: memoryUsage = -1 } = {}, disk = [] } = metrics; + + const alerts: Record = { + cpu: cpuThreshold !== -1 && cpuUsage > cpuThreshold ? true : false, + memory: memoryThreshold !== -1 && memoryUsage > memoryThreshold ? true : false, + disk: disk?.some((d) => diskThreshold !== -1 && typeof d?.usage_percent === "number" && d?.usage_percent > diskThreshold) ?? false, + }; + + const alertsToSend = []; + const discordEmbeds = []; + const monitorInfoFields = [ + { name: "Monitor", value: monitor.name, inline: true }, + { name: "URL", value: monitor.url, inline: false }, + ]; + const goToIncidentField = { name: `Go to incident`, value: `${clientHost}/infrastructure/${monitor.id}` }; + const formatDiscordAlert = { + cpu: () => ({ + title: "CPU alert", + description: `Your current CPU usage (${(cpuUsage * 100).toFixed(0)}%) is above your threshold (${(cpuThreshold * 100).toFixed(0)}%)`, + color: 15548997, + fields: [...monitorInfoFields, goToIncidentField], + footer: { text: "Checkmate" }, + }), + + memory: () => ({ + title: "Memory alert", + description: `Your current memory usage (${(memoryUsage * 100).toFixed(0)}%) is above your threshold (${(memoryThreshold * 100).toFixed(0)}%)`, + color: 15548997, + fields: [...monitorInfoFields, goToIncidentField], + footer: { text: "Checkmate" }, + }), + + disk: () => ({ + title: "Disk alert", + description: `Your current disk usage is above your threshold (${(diskThreshold * 100).toFixed(0)}%)`, + color: 15548997, + footer: { text: "Checkmate" }, + fields: [ + ...monitorInfoFields, + ...(Array.isArray(disk) ? disk : []).map((d: any, idx: number) => ({ + name: `Disk ${idx}`, + value: `${(d?.usage_percent * 100).toFixed(0)}%`, + inline: true, + })), + goToIncidentField, + ], + }), + }; + const alertTypes = ["cpu", "memory", "disk"] as const; + const alertThresholdKeyMap: Record<(typeof alertTypes)[number], "cpuAlertThreshold" | "memoryAlertThreshold" | "diskAlertThreshold"> = { + cpu: "cpuAlertThreshold", + memory: "memoryAlertThreshold", + disk: "diskAlertThreshold", + }; + for (const type of alertTypes) { + const thresholdKey = alertThresholdKeyMap[type]; + // Iterate over each alert type to see if any need to be decremented + if (alerts[type] === true) { + const nextValue = ((monitor[thresholdKey] ?? monitor.alertThreshold) as number) - 1; + monitor[thresholdKey] = nextValue; // Decrement threshold if an alert is triggered + + if (monitor[thresholdKey] <= 0) { + // If threshold drops below 0, reset and send notification + monitor[thresholdKey] = monitor.alertThreshold; + + const formatAlert = { + cpu: () => `Your current CPU usage (${(cpuUsage * 100).toFixed(0)}%) is above your threshold (${(cpuThreshold * 100).toFixed(0)}%)`, + memory: () => + `Your current memory usage (${(memoryUsage * 100).toFixed(0)}%) is above your threshold (${(memoryThreshold * 100).toFixed(0)}%)`, + disk: () => + `Your current disk usage: ${disk + .map((d, idx) => `(Disk${idx}: ${(d?.usage_percent ?? 0 * 100).toFixed(0)}%)`) + .join(", ")} is above your threshold (${(diskThreshold * 100).toFixed(0)}%)`, + }; + alertsToSend.push(formatAlert[type]()); + discordEmbeds.push(formatDiscordAlert[type]()); + } + } + } + const discordPayload = discordEmbeds.length ? { embeds: discordEmbeds } : null; + return { alertsToSend, discordPayload }; +}; + +export const buildHardwareNotificationMessage = (clientHost: string, alerts: any, monitor: Monitor) => { + const alertsHeader = [`Monitor: ${monitor.name}`, `URL: ${monitor.url}`]; + const alertFooter = [`Go to incident: ${clientHost}/infrastructure/${monitor.id}`]; + const alertText = alerts.length > 0 ? [...alertsHeader, ...alerts, ...alertFooter] : []; + return alertText.map((alert) => alert).join("\n"); +}; + +export const buildHardwareWebhookBody = (alerts: string[], monitor: Monitor): string => { + const content = alerts.map((alert) => alert).join("\n"); + return content; +}; + +export const shouldSendHardwareAlert = (monitor: Monitor, networkResponse: MonitorStatusResponse): boolean => { + const thresholds = monitor.thresholds || {}; + const { usage_cpu: cpuThreshold = -1, usage_memory: memoryThreshold = -1, usage_disk: diskThreshold = -1 } = thresholds; + + const payload = networkResponse?.payload as HardwareStatusPayload; + const metrics = payload.data || {}; + const { cpu: { usage_percent: cpuUsage = -1 } = {}, memory: { usage_percent: memoryUsage = -1 } = {}, disk = [] } = metrics; + + const cpuBreach = cpuThreshold !== -1 && cpuUsage > cpuThreshold; + if (cpuBreach && ((monitor.cpuAlertThreshold ?? monitor.alertThreshold) as number) - 1 <= 0) { + return true; + } + + const memoryBreach = memoryThreshold !== -1 && memoryUsage > memoryThreshold; + if (memoryBreach && ((monitor.memoryAlertThreshold ?? monitor.alertThreshold) as number) - 1 <= 0) { + return true; + } + + const diskBreach = disk?.some((d) => diskThreshold !== -1 && typeof d?.usage_percent === "number" && d?.usage_percent > diskThreshold); + if (diskBreach && ((monitor.diskAlertThreshold ?? monitor.alertThreshold) as number) - 1 <= 0) { + return true; + } + + return false; +}; + +export const buildWebhookBody = (monitor: Monitor, monitorStatusResponse: MonitorStatusResponse) => { + const { status, code } = monitorStatusResponse; + const { localTimeZone, localTime, utcTime } = getTime(); + return `Monitor: ${monitor.name}\nLocal Time (${localTimeZone}): ${localTime}\nUTC Time: ${utcTime}\nStatus: ${status ? "UP" : "DOWN"}\nStatus Code: ${code}\n\u200B\n`; +}; + +export const buildHardwareEmail = async (emailService: any, monitor: Monitor, alerts: string[]) => { + const template = "hardwareIncidentTemplate"; + const context = { monitor: monitor.name, url: monitor.url, alerts }; + const html = await emailService.buildEmail(template, context); + return html; +}; + +export const buildEmail = async (emailService: any, monitor: Monitor): Promise => { + const template = monitor.status === true ? "serverIsUpTemplate" : "serverIsDownTemplate"; + const context = { monitor: monitor.name, url: monitor.url }; + const html = await emailService.buildEmail(template, context); + return html; +}; + +export const buildDiscordBody = (monitor: Monitor, monitorStatusResponse: MonitorStatusResponse) => { + const { localTime, utcTime } = getTime(); + let body = { + embeds: [ + { + title: `Monitor name: ${monitor.name}`, + color: monitorStatusResponse.status ? 5763719 : 15548997, + + fields: [ + { name: "Monitor", value: monitor.name, inline: false }, + { name: "Status", value: monitorStatusResponse.status ? "Up" : "Down", inline: false }, + { name: "Status Code", value: String(monitorStatusResponse.code), inline: false }, + { name: "Time", value: `${localTime} (Local) / ${utcTime} (UTC)`, inline: false }, + { name: "URL", value: monitor.url, inline: false }, + ], + footer: { text: "Checkmate" }, + }, + ], + }; + return body; +}; + +export const buildTestEmail = async (emailService: any) => { + const context = { testName: "Monitoring System" }; + const html = await emailService.buildEmail("testEmailTemplate", context); + return html; +}; + +export const getTestMessage = () => { + return "This is a test notification from Checkmate"; +}; diff --git a/server/src/service/infrastructure/notificationProviders/webhook.ts b/server/src/service/infrastructure/notificationProviders/webhook.ts new file mode 100644 index 000000000..9e743ae53 --- /dev/null +++ b/server/src/service/infrastructure/notificationProviders/webhook.ts @@ -0,0 +1,84 @@ +const SERVICE_NAME = "WebhookProvider"; +import type { Monitor, Alert, Notification, MonitorStatusResponse } from "@/types/index.js"; +import { INotificationProvider } from "@/service/index.js"; +import { + buildHardwareAlerts, + buildHardwareWebhookBody, + buildWebhookBody, + getTestMessage, +} from "@/service/infrastructure/notificationProviders/utils.js"; +import got from "got"; + +export class WebhookProvider implements INotificationProvider { + private logger: any; + + constructor(logger: any) { + this.logger = logger; + } + private getHardwareContent = (monitor: Monitor, monitorStatusResponse: MonitorStatusResponse) => { + const { alertsToSend } = buildHardwareAlerts("HOST_PLACEHOLDER", monitor, monitorStatusResponse); + const body = buildHardwareWebhookBody(alertsToSend, monitor); + return body; + }; + + private getContent = (monitor: Monitor, monitorStatusResponse: MonitorStatusResponse): string => { + const body = buildWebhookBody(monitor, monitorStatusResponse); + return body; + }; + + sendAlert = async (notification: Notification, monitor: Monitor, monitorStatusResponse: MonitorStatusResponse) => { + let body; + if (monitor.type === "hardware") { + body = this.getHardwareContent(monitor, monitorStatusResponse); + } else { + body = this.getContent(monitor, monitorStatusResponse); + } + + if (!notification.address) { + return false; + } + + try { + await got.post(notification.address, { + json: { text: body }, + headers: { + "Content-Type": "application/json", + }, + }); + return true; + } catch (error) { + const err = error as Error; + this.logger.warn({ + message: "Webhook alert failed", + service: SERVICE_NAME, + method: "sendAlert", + stack: err?.stack, + }); + return false; + } + }; + + sendTestAlert = async (notification: Notification) => { + if (!notification.address) { + return false; + } + try { + await got.post(notification.address, { + json: { text: getTestMessage() }, + headers: { + "Content-Type": "application/json", + }, + }); + return true; + } catch (error) { + const err = error as Error; + this.logger.warn({ + message: "Webhook test alert failed", + service: SERVICE_NAME, + method: "sendTestAlert", + stack: err?.stack, + }); + return false; + } + }; +} diff --git a/server/src/service/infrastructure/notificationService.js b/server/src/service/infrastructure/notificationService.js deleted file mode 100644 index 8c6fb063f..000000000 --- a/server/src/service/infrastructure/notificationService.js +++ /dev/null @@ -1,128 +0,0 @@ -const SERVICE_NAME = "NotificationService"; -import Matrix from "./notificationProviders/matrix.js"; - -class NotificationService { - static SERVICE_NAME = SERVICE_NAME; - - constructor({ emailService, db, logger, networkService, stringService, notificationUtils }) { - this.emailService = emailService; - this.db = db; - this.logger = logger; - this.networkService = networkService; - this.stringService = stringService; - this.notificationUtils = notificationUtils; - } - - get serviceName() { - return NotificationService.SERVICE_NAME; - } - - sendNotification = async ({ notification, subject, content, html, discordContent = null, webhookBody = null }) => { - const { type, address } = notification; - - if (type === "email") { - const messageId = await this.emailService.sendEmail(address, subject, html); - if (!messageId) return false; - return true; - } - - // Create a body for webhooks - let body = { text: content }; - if (type === "discord") { - body = !discordContent ? { content } : discordContent; - } - if (type === "webhook") { - body = !webhookBody ? { content } : webhookBody; - } - if (type === "slack" || type === "discord" || type === "webhook") { - const response = await this.networkService.requestWebhook(type, address, body); - return response.status; - } - if (type === "pager_duty") { - const response = await this.networkService.requestPagerDuty({ - message: content, - monitorUrl: subject, - routingKey: address, - }); - - return response; - } - if (type === "matrix") { - const { friendlyName, homeserverUrl, accessToken, roomId } = notification; - const monitorName = subject; - const message = content; - const matrix = new Matrix({ networkService: this.networkService, logger: this.logger }); - const success = await matrix.send({ friendlyName, homeserverUrl, accessToken, roomId, message, monitorName }); - return success; - } - }; - - async handleNotifications(networkResponse) { - const { monitor, statusChanged, prevStatus } = networkResponse; - const { type } = monitor; - if (type !== "hardware" && statusChanged === false) return false; - // if prevStatus is undefined, monitor is resuming, we're done - if (type !== "hardware" && prevStatus === undefined) return false; - - const notificationIDs = networkResponse.monitor?.notifications ?? []; - if (notificationIDs.length === 0) return false; - if (networkResponse.monitor.type === "hardware") { - const thresholds = networkResponse?.monitor?.thresholds; - - if (thresholds === undefined) return false; // No thresholds set, we're done - const metrics = networkResponse?.payload?.data ?? null; - if (metrics === null) return false; // No metrics, we're done - - const [alerts, discordContent] = await this.notificationUtils.buildHardwareAlerts(networkResponse); - if (alerts.length === 0) return false; - - const { subject, html } = await this.notificationUtils.buildHardwareEmail(networkResponse, alerts); - const content = await this.notificationUtils.buildHardwareNotificationMessage(alerts, monitor); - const webhookBody = await this.notificationUtils.buildHardwareWebhookBody(alerts, monitor); - const success = await this.notifyAll({ notificationIDs, subject, html, content, discordContent, webhookBody }); - return success; - } - - // Status monitors - const { subject, html } = await this.notificationUtils.buildStatusEmail(networkResponse); - const [content, discordContent] = await this.notificationUtils.buildWebhookMessage(networkResponse); - const success = this.notifyAll({ notificationIDs, subject, html, content, discordContent }); - return success; - } - - async notifyAll({ notificationIDs, subject, html, content, discordContent = null, webhookBody = null }) { - const notifications = await this.db.notificationModule.getNotificationsByIds(notificationIDs); - // Map each notification to a test promise - const promises = notifications.map(async (notification) => { - try { - await this.sendNotification({ notification, subject, content, html, discordContent, webhookBody }); - return true; - } catch (err) { - return false; - } - }); - - const results = await Promise.all(promises); - return results.every((r) => r === true); - } - - async getTestNotification() { - const html = await this.notificationUtils.buildTestEmail(); - const content = "This is a test notification"; - const subject = "Test Notification"; - return { subject, html, content }; - } - - async testAllNotifications(notificationIDs) { - const { subject, html, content } = await this.getTestNotification(); - return this.notifyAll({ notificationIDs, subject, html, content }); - } - - async sendTestNotification(notification) { - const { subject, html, content } = await this.getTestNotification(); - const success = await this.sendNotification({ notification, subject, content, html }); - return success; - } -} - -export default NotificationService; diff --git a/server/src/service/infrastructure/notificationUtils.js b/server/src/service/infrastructure/notificationUtils.js deleted file mode 100644 index 106c8f349..000000000 --- a/server/src/service/infrastructure/notificationUtils.js +++ /dev/null @@ -1,205 +0,0 @@ -const SERVICE_NAME = "NotificationUtils"; - -class NotificationUtils { - static SERVICE_NAME = SERVICE_NAME; - - constructor({ stringService, emailService, settingsService }) { - this.stringService = stringService; - this.emailService = emailService; - this.settingsService = settingsService; - } - - get serviceName() { - return NotificationUtils.SERVICE_NAME; - } - - buildTestEmail = async () => { - const context = { testName: "Monitoring System" }; - const html = await this.emailService.buildEmail("testEmailTemplate", context); - return html; - }; - - buildStatusEmail = async (networkResponse) => { - const { monitor, status, prevStatus } = networkResponse; - const template = prevStatus === false ? "serverIsUpTemplate" : "serverIsDownTemplate"; - const context = { monitor: monitor.name, url: monitor.url }; - const subject = `Monitor ${monitor.name} is ${status === true ? "up" : "down"}`; - const html = await this.emailService.buildEmail(template, context); - return { subject, html }; - }; - - buildWebhookMessage = (networkResponse) => { - const { monitor, status, code, timestamp } = networkResponse; - // Format timestamp using the local system timezone - const formatTime = (timestamp) => { - const date = new Date(timestamp); - - // Get timezone abbreviation and format the date - const timeZoneAbbr = date.toLocaleTimeString("en-US", { timeZoneName: "short" }).split(" ").pop(); - - // Format the date with readable format - return ( - date - .toLocaleString("en-US", { - year: "numeric", - month: "2-digit", - day: "2-digit", - hour: "2-digit", - minute: "2-digit", - second: "2-digit", - hour12: false, - }) - .replace(/(\d+)\/(\d+)\/(\d+),\s/, "$3-$1-$2 ") + - " " + - timeZoneAbbr - ); - }; - - // Get formatted time - const formattedTime = timestamp ? formatTime(timestamp) : formatTime(new Date().getTime()); - - // Create different messages based on status with extra spacing - let messageText; - if (status === true) { - messageText = this.stringService.monitorUpAlert - .replace("{monitorName}", monitor.name) - .replace("{time}", formattedTime) - .replace("{code}", code || "Unknown"); - } else { - messageText = this.stringService.monitorDownAlert - .replace("{monitorName}", monitor.name) - .replace("{time}", formattedTime) - .replace("{code}", code || "Unknown"); - } - const dn = this.stringService.discordNotification; - let discordMessageText = { - embeds: [ - { - title: status - ? dn.uptimeAlert.replace("{monitorName}", monitor?.name ?? dn.unknown) - : dn.downtimeAlert.replace("{monitorName}", monitor?.name ?? dn.unknown), - color: status ? 5763719 : 15548997, - - fields: [ - { name: dn.monitor, value: monitor?.name ?? dn.unknown, inline: true }, - { name: dn.status, value: status ? dn.up : dn.down, inline: true }, - { name: dn.statusCode, value: String(code ?? dn.unknown), inline: true }, - { name: dn.time, value: formattedTime, inline: true }, - { name: dn.url, value: monitor?.url ?? dn.unknown, inline: false }, - ], - footer: { text: dn.checkmate }, - }, - ], - }; - return [messageText, discordMessageText]; - }; - - buildHardwareAlerts = async (networkResponse) => { - const monitor = networkResponse?.monitor; - const thresholds = networkResponse?.monitor?.thresholds; - const { usage_cpu: cpuThreshold = -1, usage_memory: memoryThreshold = -1, usage_disk: diskThreshold = -1 } = thresholds; - - const metrics = networkResponse?.payload?.data; - const { cpu: { usage_percent: cpuUsage = -1 } = {}, memory: { usage_percent: memoryUsage = -1 } = {}, disk = [] } = metrics; - - const { clientHost } = this.settingsService.getSettings(); - - const alerts = { - cpu: cpuThreshold !== -1 && cpuUsage > cpuThreshold ? true : false, - memory: memoryThreshold !== -1 && memoryUsage > memoryThreshold ? true : false, - disk: disk?.some((d) => diskThreshold !== -1 && typeof d?.usage_percent === "number" && d?.usage_percent > diskThreshold) ?? false, - }; - - const alertsToSend = []; - const discordEmbeds = []; - const monitorInfoFields = [ - { name: "Monitor", value: monitor.name, inline: true }, - { name: "URL", value: monitor.url, inline: false }, - ]; - const goToIncidentField = { name: `Go to incident`, value: `${clientHost}/infrastructure/${monitor._id}` }; - const formatDiscordAlert = { - cpu: () => ({ - title: "CPU alert", - description: `Your current CPU usage (${(cpuUsage * 100).toFixed(0)}%) is above your threshold (${(cpuThreshold * 100).toFixed(0)}%)`, - color: 15548997, - fields: [...monitorInfoFields, goToIncidentField], - footer: { text: "Checkmate" }, - }), - - memory: () => ({ - title: "Memory alert", - description: `Your current memory usage (${(memoryUsage * 100).toFixed(0)}%) is above your threshold (${(memoryThreshold * 100).toFixed(0)}%)`, - color: 15548997, - fields: [...monitorInfoFields, goToIncidentField], - footer: { text: "Checkmate" }, - }), - - disk: () => ({ - title: "Disk alert", - description: `Your current disk usage is above your threshold (${(diskThreshold * 100).toFixed(0)}%)`, - color: 15548997, - footer: { text: "Checkmate" }, - fields: [ - ...monitorInfoFields, - ...(Array.isArray(disk) ? disk : []).map((d, idx) => ({ - name: `Disk ${idx}`, - value: `${(d?.usage_percent * 100).toFixed(0)}%`, - inline: true, - })), - goToIncidentField, - ], - }), - }; - const alertTypes = ["cpu", "memory", "disk"]; - for (const type of alertTypes) { - // Iterate over each alert type to see if any need to be decremented - if (alerts[type] === true) { - monitor[`${type}AlertThreshold`]--; // Decrement threshold if an alert is triggered - - if (monitor[`${type}AlertThreshold`] <= 0) { - // If threshold drops below 0, reset and send notification - monitor[`${type}AlertThreshold`] = monitor.alertThreshold; - - const formatAlert = { - cpu: () => `Your current CPU usage (${(cpuUsage * 100).toFixed(0)}%) is above your threshold (${(cpuThreshold * 100).toFixed(0)}%)`, - memory: () => - `Your current memory usage (${(memoryUsage * 100).toFixed(0)}%) is above your threshold (${(memoryThreshold * 100).toFixed(0)}%)`, - disk: () => - `Your current disk usage: ${disk - .map((d, idx) => `(Disk${idx}: ${(d.usage_percent * 100).toFixed(0)}%)`) - .join(", ")} is above your threshold (${(diskThreshold * 100).toFixed(0)}%)`, - }; - alertsToSend.push(formatAlert[type]()); - discordEmbeds.push(formatDiscordAlert[type]()); - } - } - } - await monitor.save(); - const discordPayload = discordEmbeds.length ? { embeds: discordEmbeds } : null; - return [alertsToSend, discordPayload]; - }; - - buildHardwareEmail = async (networkResponse, alerts) => { - const { monitor } = networkResponse; - const template = "hardwareIncidentTemplate"; - const context = { monitor: monitor.name, url: monitor.url, alerts }; - const subject = `Monitor ${monitor.name} infrastructure alerts`; - const html = await this.emailService.buildEmail(template, context); - return { subject, html }; - }; - - buildHardwareNotificationMessage = (alerts, monitor) => { - const { clientHost } = this.settingsService.getSettings(); - const alertsHeader = [`Monitor: ${monitor.name}`, `URL: ${monitor.url}`]; - const alertFooter = [`Go to incident: ${clientHost}/infrastructure/${monitor._id}`]; - const alertText = alerts.length > 0 ? [...alertsHeader, ...alerts, ...alertFooter] : []; - return alertText.map((alert) => alert).join("\n"); - }; - buildHardwareWebhookBody = (alerts, monitor) => { - const content = alerts.map((alert) => alert).join("\n"); - const body = { text: content, name: monitor.name, url: monitor.url }; - return body; - }; -} - -export default NotificationUtils; diff --git a/server/src/service/infrastructure/notificationsService.ts b/server/src/service/infrastructure/notificationsService.ts new file mode 100644 index 000000000..7ca52945e --- /dev/null +++ b/server/src/service/infrastructure/notificationsService.ts @@ -0,0 +1,150 @@ +import type { HardwareStatusPayload, Monitor, MonitorStatusResponse, Notification } from "@/types/index.js"; +import { shouldSendHardwareAlert } from "@/service/infrastructure/notificationProviders/utils.js"; +import { INotificationsRepository } from "@/repositories/index.js"; +import { INotificationProvider } from "./notificationProviders/INotificationProvider.js"; +export interface INotificationsService { + handleNotifications: ( + monitor: Monitor, + monitorStatusResponse: MonitorStatusResponse, + prevStatus: boolean | undefined, + statusChanged: boolean + ) => Promise; + sendTestNotification: (notification: Notification) => Promise; + testAllNotifications: (notificationIds: string[]) => Promise; +} + +const SERVICE_NAME = "NotificationsService"; + +export class NotificationsService implements INotificationsService { + static SERVICE_NAME = SERVICE_NAME; + + private notificationsRepository: INotificationsRepository; + private webhookProvider: INotificationProvider; + private emailProvider: INotificationProvider; + private slackProvider: INotificationProvider; + private discordProvider: INotificationProvider; + private pagerDutyProvider: INotificationProvider; + private matrixProvider: INotificationProvider; + private logger: any; + + constructor( + notificationsRepository: INotificationsRepository, + webhookProvider: INotificationProvider, + emailProvider: INotificationProvider, + slackProvider: INotificationProvider, + discordProvider: INotificationProvider, + pagerDutyProvider: INotificationProvider, + matrixProvider: INotificationProvider, + logger: any + ) { + this.notificationsRepository = notificationsRepository; + this.webhookProvider = webhookProvider; + this.emailProvider = emailProvider; + this.slackProvider = slackProvider; + this.discordProvider = discordProvider; + this.pagerDutyProvider = pagerDutyProvider; + this.matrixProvider = matrixProvider; + this.logger = logger; + } + + private send = async (notification: Notification, monitor: Monitor, monitorStatusResponse: MonitorStatusResponse): Promise => { + switch (notification.type) { + case "email": + return await this.emailProvider.sendAlert(notification, monitor, monitorStatusResponse); + case "slack": + return await this.slackProvider.sendAlert(notification, monitor, monitorStatusResponse); + case "discord": + return await this.discordProvider.sendAlert(notification, monitor, monitorStatusResponse); + case "pager_duty": + return await this.pagerDutyProvider.sendAlert(notification, monitor, monitorStatusResponse); + case "matrix": + return await this.matrixProvider.sendAlert(notification, monitor, monitorStatusResponse); + case "webhook": + return await this.webhookProvider.sendAlert(notification, monitor, monitorStatusResponse); + default: + return false; + } + }; + + private sendNotifications = async (monitor: Monitor, monitorStatusResponse: MonitorStatusResponse) => { + const notificationIds = monitor.notifications ?? []; + const notifications = await this.notificationsRepository.findNotificationsByIds(notificationIds); + const tasks = notifications.map((notification) => this.send(notification, monitor, monitorStatusResponse)); + const outcomes = await Promise.all(tasks); + const succeeded = outcomes.filter(Boolean).length; + const failed = outcomes.length - succeeded; + if (failed > 0) { + this.logger.warn({ + message: `Notification send completed with ${succeeded} success, ${failed} failure(s)`, + service: SERVICE_NAME, + method: "getMonitorJob", + }); + } + // Return true if all notificaitons succeeded + return succeeded === notifications.length; + }; + + handleNotifications = async ( + monitor: Monitor, + monitorStatusResponse: MonitorStatusResponse, + prevStatus: boolean | undefined, + statusChanged: boolean + ) => { + const { type } = monitor; + const payload = monitorStatusResponse.payload as HardwareStatusPayload; + // If this is a non-hardeware type monitor and status did not change, we're done + if (type !== "hardware" && statusChanged === false) return false; + // if prevStatus is undefined, monitor is resuming, we're done + if (type !== "hardware" && prevStatus === undefined) return false; + + // Deal with hardware thresholds + if (type === "hardware") { + const thresholds = monitor.thresholds; + + if (thresholds === undefined) return false; // No thresholds set, we're done + const metrics = payload?.data ?? null; + if (metrics === null) return false; // No metrics, we're done + + // We should send a notificaiton + + const shouldSend = shouldSendHardwareAlert(monitor, monitorStatusResponse); + if (shouldSend === false) return false; + + return await this.sendNotifications(monitor, monitorStatusResponse); + } + + // We should send a notification for non-hardware monitor status change + return await this.sendNotifications(monitor, monitorStatusResponse); + }; + + sendTestNotification = async (notification: Notification) => { + switch (notification.type) { + case "email": + return await this.emailProvider.sendTestAlert(notification); + case "slack": + return await this.slackProvider.sendTestAlert(notification); + case "discord": + return await this.discordProvider.sendTestAlert(notification); + case "pager_duty": + return await this.pagerDutyProvider.sendTestAlert(notification); + case "matrix": + return await this.matrixProvider.sendTestAlert(notification); + case "webhook": + return await this.webhookProvider.sendTestAlert(notification); + default: + return false; + } + }; + + testAllNotifications = async (notificationIds: string[]) => { + const notifications = await this.notificationsRepository.findNotificationsByIds(notificationIds); + const tasks = notifications.map((notification) => this.sendTestNotification(notification)); + const outcomes = await Promise.all(tasks); + const succeeded = outcomes.filter(Boolean).length; + const failed = outcomes.length - succeeded; + if (failed > 0) { + return false; + } + return true; + }; +} diff --git a/server/src/service/infrastructure/statusService.js b/server/src/service/infrastructure/statusService.js deleted file mode 100755 index e849bbb83..000000000 --- a/server/src/service/infrastructure/statusService.js +++ /dev/null @@ -1,452 +0,0 @@ -import MonitorStats from "../../db/models/MonitorStats.js"; -import { CheckModel } from "@/db/models/index.js"; -const SERVICE_NAME = "StatusService"; - -class StatusService { - static SERVICE_NAME = SERVICE_NAME; - - /** - * @param {{ - * db: any - * logger: any - * buffer: import("./bufferService.js").BufferService - * incidentService: import("../business/incidentService.js").IncidentService - * monitorsRepository: any - * }} - */ - constructor({ db, logger, buffer, incidentService, monitorsRepository }) { - this.db = db; - this.logger = logger; - this.buffer = buffer; - this.incidentService = incidentService; - this.monitorsRepository = monitorsRepository; - } - - get serviceName() { - return StatusService.SERVICE_NAME; - } - - async updateRunningStats({ monitor, networkResponse }) { - try { - const monitorId = monitor.id; - const { responseTime, status } = networkResponse; - // Get stats - let stats = await MonitorStats.findOne({ monitorId }); - if (!stats) { - stats = new MonitorStats({ - monitorId, - avgResponseTime: 0, - totalChecks: 0, - totalUpChecks: 0, - totalDownChecks: 0, - uptimePercentage: 0, - lastCheck: null, - }); - } - - // Update stats - - // Last response time - stats.lastResponseTime = responseTime; - - // Avg response time: - let avgResponseTime = stats.avgResponseTime; - if (typeof responseTime !== "undefined" && responseTime !== null) { - if (avgResponseTime === 0) { - avgResponseTime = responseTime; - } else { - avgResponseTime = (avgResponseTime * (stats.totalChecks - 1) + responseTime) / stats.totalChecks; - } - } - stats.avgResponseTime = avgResponseTime; - - // Total checks - stats.totalChecks++; - if (status === true) { - stats.totalUpChecks++; - // Update the timeSinceLastFailure if needed - if (stats.timeOfLastFailure === 0) { - stats.timeOfLastFailure = new Date().getTime(); - } - } else { - stats.totalDownChecks++; - stats.timeOfLastFailure = 0; - } - - // Calculate uptime percentage - let uptimePercentage; - if (stats.totalChecks > 0) { - uptimePercentage = stats.totalUpChecks / stats.totalChecks; - } else { - uptimePercentage = status === true ? 100 : 0; - } - stats.uptimePercentage = uptimePercentage; - - // latest check - stats.lastCheckTimestamp = new Date().getTime(); - - await stats.save(); - return true; - } catch (error) { - this.logger.error({ - service: this.SERVICE_NAME, - message: error.message, - method: "updateRunningStats", - stack: error.stack, - }); - return false; - } - } - - getStatusString = (status) => { - if (status === true) return "up"; - if (status === false) return "down"; - return "unknown"; - }; - - /** - * Saves check if needed and adds to incident buffer - * Removes check from checks buffer if it was saved immediately - * - * @param {Object} check - The check object - * @param {Object} monitor - The monitor object - * @param {string} action - The incident action ("create" or "resolve") - * @param {string} errorContext - Context for error messages - * @returns {Promise} - */ - handleIncidentForCheck = async (check, monitor, action, errorContext = "incident handling") => { - try { - let savedCheck = check; - - if (!check._id) { - try { - const checkModel = new CheckModel(check); - savedCheck = await checkModel.save(); - - this.buffer.removeCheckFromBuffer(check); - } catch (checkError) { - this.logger.error({ - service: this.SERVICE_NAME, - method: "handleIncidentForCheck", - message: `Failed to save check immediately for ${errorContext}: ${checkError.message}`, - monitorId: monitor.id, - stack: checkError.stack, - }); - savedCheck = null; - } - } - - if (savedCheck && savedCheck._id) { - try { - this.buffer.addIncidentToBuffer({ monitor, check: savedCheck, action }); - } catch (incidentError) { - this.logger.error({ - service: this.SERVICE_NAME, - method: "handleIncidentForCheck", - message: `Failed to add incident to buffer for ${errorContext}: ${incidentError.message}`, - monitorId: monitor.id, - action, - stack: incidentError.stack, - }); - } - } - } catch (error) { - this.logger.error({ - service: this.SERVICE_NAME, - method: "handleIncidentForCheck", - message: `Error in ${errorContext}: ${error.message}`, - monitorId: monitor?.id, - stack: error.stack, - }); - } - }; - /** - * Updates the status of a monitor based on the network response. - * - * @param {Object} networkResponse - The network response containing monitorId and status. - * @param {string} networkResponse.monitorId - The ID of the monitor. - * @param {string} networkResponse.status - The new status of the monitor. - * @returns {Promise} - A promise that resolves to an object containinfg the monitor, statusChanged flag, and previous status if the status changed, or false if an error occurred. - * @returns {Promise} returnObject - The object returned by the function. - * @returns {Object} returnObject.monitor - The monitor object. - * @returns {boolean} returnObject.statusChanged - Flag indicating if the status has changed. - * @returns {boolean} returnObject.prevStatus - The previous status of the monitor - */ - updateStatus = async (networkResponse) => { - const check = this.buildCheck(networkResponse); - await this.insertCheck(check); - try { - const { monitorId, status, code } = networkResponse; - - const monitor = await this.monitorsRepository.findById(monitorId); - - // Update running stats - this.updateRunningStats({ monitor, networkResponse }); - - // If the status window size has changed, empty - while (monitor.statusWindow.length > monitor.statusWindowSize) { - monitor.statusWindow.shift(); - } - - // Update status sliding window - monitor.statusWindow.push(status); - if (monitor.statusWindow.length > monitor.statusWindowSize) { - monitor.statusWindow.shift(); - } - - if (monitor.status === undefined || monitor.status === null) { - monitor.status = status; - } - - let newStatus = monitor.status; - let statusChanged = false; - const prevStatus = monitor.status; - - // Return early if not enough data points - if (monitor.statusWindow.length < monitor.statusWindowSize) { - const updated = await this.monitorsRepository.update(monitor.id, monitor); - return { - monitor: updated, - statusChanged: false, - prevStatus, - code, - timestamp: Date.now(), - }; - } - - // Check if threshold has been met - const failures = monitor.statusWindow.filter((s) => s === false).length; - const failureRate = (failures / monitor.statusWindow.length) * 100; - - // If threshold has been met and the monitor is not already down, mark down: - if (failureRate >= monitor.statusWindowThreshold && monitor.status !== false) { - newStatus = false; - statusChanged = true; - } - // If the failure rate is below the threshold and the monitor is down, recover: - else if (failureRate < monitor.statusWindowThreshold && monitor.status === false) { - newStatus = true; - statusChanged = true; - } - - if (statusChanged) { - this.logger.info({ - service: this.SERVICE_NAME, - message: `${monitor.name} went from ${this.getStatusString(prevStatus)} to ${this.getStatusString(newStatus)}`, - prevStatus, - newStatus, - }); - - if (newStatus === false) { - await this.handleIncidentForCheck(check, monitor, "create", "status change to down"); - } else if (prevStatus === false) { - await this.handleIncidentForCheck(check, monitor, "resolve", "status change to up"); - } - } - - if (monitor.status === false && !statusChanged) { - try { - const lastManuallyResolvedIncident = await this.db.incidentModule.getLastManuallyResolvedIncident(monitor.id); - - let calculatedFailureRate = failureRate; - - if (lastManuallyResolvedIncident && lastManuallyResolvedIncident.endTime) { - try { - const checksAfterResolution = await Check.find({ - monitorId: monitor.id, - createdAt: { $gt: lastManuallyResolvedIncident.endTime }, - }) - .sort({ createdAt: 1 }) - .limit(monitor.statusWindowSize) - .select("status") - .lean(); - - if (checksAfterResolution.length > 0) { - const checksStatuses = checksAfterResolution.map((c) => c.status); - const failuresAfterResolution = checksStatuses.filter((s) => s === false).length; - calculatedFailureRate = (failuresAfterResolution / monitor.statusWindow.length) * 100; - } else { - calculatedFailureRate = 0; - } - } catch (checkQueryError) { - this.logger.error({ - service: this.SERVICE_NAME, - method: "updateStatus", - message: `Failed to query checks after manual resolution: ${checkQueryError.message}`, - monitorId: monitor.id, - stack: checkQueryError.stack, - }); - } - } - - if (calculatedFailureRate >= monitor.statusWindowThreshold) { - await this.handleIncidentForCheck(check, monitor, "create", "threshold check without status change"); - } - } catch (error) { - this.logger.error({ - service: this.SERVICE_NAME, - method: "updateStatus", - message: `Error handling threshold check without status change: ${error.message}`, - monitorId: monitor.id, - stack: error.stack, - }); - } - } - - monitor.status = newStatus; - const updated = await this.monitorsRepository.update(monitor.id, monitor); - - return { - monitor: updated, - statusChanged, - prevStatus, - code, - timestamp: new Date().getTime(), - }; - } catch (error) { - error.service = this.SERVICE_NAME; - error.method = "updateStatus"; - throw error; - } - }; - - /** - * Builds a check object from the network response. - * - * @param {Object} networkResponse - The network response object. - * @param {string} networkResponse.monitorId - The monitor ID. - * @param {string} networkResponse.type - The type of the response. - * @param {string} networkResponse.status - The status of the response. - * @param {number} networkResponse.responseTime - The response time. - * @param {number} networkResponse.code - The status code. - * @param {string} networkResponse.message - The message. - * @param {Object} networkResponse.payload - The payload of the response. - * @returns {Object} The check object. - */ - buildCheck = (networkResponse) => { - const { - monitorId, - teamId, - type, - status, - responseTime, - code, - message, - payload, - first_byte_took, - body_read_took, - dns_took, - conn_took, - connect_took, - tls_took, - timings, - } = networkResponse; - - const check = { - metadata: { - monitorId, - teamId, - type, - }, - status, - statusCode: code, - responseTime, - timings: timings || {}, - message, - first_byte_took, - body_read_took, - dns_took, - conn_took, - connect_took, - tls_took, - }; - - if (type === "pagespeed") { - if (typeof payload === "undefined") { - this.logger.warn({ - message: "Failed to build check", - service: this.SERVICE_NAME, - method: "buildCheck", - details: "empty payload", - }); - return undefined; - } - const categories = payload?.lighthouseResult?.categories ?? {}; - const audits = payload?.lighthouseResult?.audits ?? {}; - const mapAudit = (audit) => { - if (!audit || typeof audit !== "object") { - return undefined; - } - return { - id: audit.id, - title: audit.title, - score: typeof audit.score === "number" ? audit.score : (audit.score ?? null), - displayValue: audit.displayValue, - numericValue: typeof audit.numericValue === "number" ? audit.numericValue : undefined, - numericUnit: audit.numericUnit, - }; - }; - check.accessibility = (categories?.accessibility?.score || 0) * 100; - check.bestPractices = (categories?.["best-practices"]?.score || 0) * 100; - check.seo = (categories?.seo?.score || 0) * 100; - check.performance = (categories?.performance?.score || 0) * 100; - check.audits = { - cls: mapAudit(audits?.["cumulative-layout-shift"]), - si: mapAudit(audits?.["speed-index"]), - fcp: mapAudit(audits?.["first-contentful-paint"]), - lcp: mapAudit(audits?.["largest-contentful-paint"]), - tbt: mapAudit(audits?.["total-blocking-time"]), - }; - } - - if (type === "hardware") { - const { cpu, memory, disk, host, net } = payload?.data ?? {}; - const { errors } = payload?.errors ?? []; - check.cpu = cpu ?? {}; - check.memory = memory ?? {}; - check.disk = disk ?? {}; - check.host = host ?? {}; - check.errors = errors ?? []; - check.capture = payload?.capture ?? {}; - check.net = net ?? {}; - } - return check; - }; - - /** - * Inserts a check into the database based on the network response. - * - * @param {Object} networkResponse - The network response object. - * @param {string} networkResponse.monitorId - The monitor ID. - * @param {string} networkResponse.type - The type of the response. - * @param {string} networkResponse.status - The status of the response. - * @param {number} networkResponse.responseTime - The response time. - * @param {number} networkResponse.code - The status code. - * @param {string} networkResponse.message - The message. - * @param {Object} networkResponse.payload - The payload of the response. - * @returns {Promise} A promise that resolves when the check is inserted. - */ - insertCheck = async (check) => { - try { - if (typeof check === "undefined") { - this.logger.warn({ - message: "Failed to build check", - service: this.SERVICE_NAME, - method: "insertCheck", - }); - return false; - } - this.buffer.addToBuffer({ check }); - return true; - } catch (error) { - this.logger.error({ - message: error.message, - service: error.service || this.SERVICE_NAME, - method: error.method || "insertCheck", - details: error.details || `Error inserting check for monitor: ${check?.monitorId}`, - stack: error.stack, - }); - } - }; -} -export default StatusService; diff --git a/server/src/service/infrastructure/statusService.ts b/server/src/service/infrastructure/statusService.ts new file mode 100755 index 000000000..3a83dbd28 --- /dev/null +++ b/server/src/service/infrastructure/statusService.ts @@ -0,0 +1,260 @@ +import { IMonitorsRepository } from "@/repositories/index.js"; +import MonitorStats from "../../db/models/MonitorStats.js"; +import { CheckModel } from "@/db/models/index.js"; +import type { + CheckErrorInfo, + Monitor, + MonitorStatusResponse, + StatusChangeResult, + Check, + HardwareStatusPayload, + PageSpeedStatusPayload, +} from "@/types/index.js"; +const SERVICE_NAME = "StatusService"; + +export interface IStatusService { + updateRunningStats({ monitor, networkResponse }: { monitor: Monitor; networkResponse: any }): Promise; + getStatusString(status: boolean | undefined): string; + handleIncidentForCheck(check: any, monitor: Monitor, action: any, errorContext?: string): Promise; + updateMonitorStatus( + statusResponse: MonitorStatusResponse, + check: Check + ): Promise; +} + +export class StatusService implements IStatusService { + static SERVICE_NAME = SERVICE_NAME; + private db: any; + private logger: any; + private buffer: any; + private monitorsRepository: IMonitorsRepository; + + constructor({ db, logger, buffer, monitorsRepository }: { db: any; logger: any; buffer: any; monitorsRepository: IMonitorsRepository }) { + this.db = db; + this.logger = logger; + this.buffer = buffer; + this.monitorsRepository = monitorsRepository; + } + + get serviceName() { + return StatusService.SERVICE_NAME; + } + + async updateRunningStats({ monitor, networkResponse }: { monitor: Monitor; networkResponse: any }) { + try { + const monitorId = monitor.id; + const { responseTime, status } = networkResponse; + // Get stats + let stats = await MonitorStats.findOne({ monitorId }); + if (!stats) { + stats = new MonitorStats({ + monitorId, + avgResponseTime: 0, + totalChecks: 0, + totalUpChecks: 0, + totalDownChecks: 0, + uptimePercentage: 0, + lastCheck: null, + }); + } + + // Update stats + + // Last response time + stats.lastResponseTime = responseTime; + + // Avg response time: + let avgResponseTime = stats.avgResponseTime; + if (typeof responseTime !== "undefined" && responseTime !== null) { + if (avgResponseTime === 0) { + avgResponseTime = responseTime; + } else { + avgResponseTime = (avgResponseTime * (stats.totalChecks - 1) + responseTime) / stats.totalChecks; + } + } + stats.avgResponseTime = avgResponseTime; + + // Total checks + stats.totalChecks++; + if (status === true) { + stats.totalUpChecks++; + // Update the timeSinceLastFailure if needed + if (stats.timeOfLastFailure === 0) { + stats.timeOfLastFailure = new Date().getTime(); + } + } else { + stats.totalDownChecks++; + stats.timeOfLastFailure = 0; + } + + // Calculate uptime percentage + let uptimePercentage; + if (stats.totalChecks > 0) { + uptimePercentage = stats.totalUpChecks / stats.totalChecks; + } else { + uptimePercentage = status === true ? 100 : 0; + } + stats.uptimePercentage = uptimePercentage; + + // latest check + stats.lastCheckTimestamp = new Date().getTime(); + + await stats.save(); + return true; + } catch (error: any) { + this.logger.error({ + service: SERVICE_NAME, + message: error.message, + method: "updateRunningStats", + stack: error.stack, + }); + return false; + } + } + + getStatusString = (status: boolean | undefined) => { + if (status === true) return "up"; + if (status === false) return "down"; + return "unknown"; + }; + + handleIncidentForCheck = async (check: Check, monitor: Monitor, action: any, errorContext = "incident handling") => { + try { + let savedCheck; + if (!check.id) { + try { + const checkModel = new CheckModel(check); + savedCheck = await checkModel.save(); + + this.buffer.removeCheckFromBuffer(check); + } catch (checkError: any) { + this.logger.error({ + service: SERVICE_NAME, + method: "handleIncidentForCheck", + message: `Failed to save check immediately for ${errorContext}: ${checkError.message}`, + monitorId: monitor.id, + stack: checkError.stack, + }); + savedCheck = null; + } + } + + if (savedCheck && savedCheck.id) { + try { + this.buffer.addIncidentToBuffer({ monitor, check: savedCheck, action }); + } catch (incidentError: any) { + this.logger.error({ + service: SERVICE_NAME, + method: "handleIncidentForCheck", + message: `Failed to add incident to buffer for ${errorContext}: ${incidentError.message}`, + monitorId: monitor.id, + action, + stack: incidentError.stack, + }); + } + } + } catch (error: any) { + this.logger.error({ + service: SERVICE_NAME, + method: "handleIncidentForCheck", + message: `Error in ${errorContext}: ${error.message}`, + monitorId: monitor?.id, + stack: error.stack, + }); + } + }; + + updateMonitorStatus = async ( + statusResponse: MonitorStatusResponse, + check: Check + ): Promise => { + try { + const { monitorId, teamId, status, code } = statusResponse; + const monitor = await this.monitorsRepository.findById(monitorId, teamId); + + // Update running stats + this.updateRunningStats({ monitor, networkResponse: statusResponse }); + + // If the status window size has changed, empty + + monitor.statusWindow = monitor.statusWindow || []; + monitor.statusWindow.push(status); + while (monitor.statusWindow.length > monitor.statusWindowSize) { + monitor.statusWindow.shift(); + } + + if (monitor.status === undefined || monitor.status === null) { + monitor.status = status; + } + + const prevStatus = monitor.status; + let newStatus = monitor.status; + let statusChanged = false; + + // Return early if not enough data points + if (monitor.statusWindow.length < monitor.statusWindowSize) { + const updated = await this.monitorsRepository.updateById(monitor.id, monitor.teamId, monitor); + return { + monitor: updated, + statusChanged: false, + prevStatus, + code, + timestamp: Date.now(), + }; + } + + // Check if threshold has been met + const failures = monitor.statusWindow.filter((s) => s === false).length; + const failureRate = (failures / monitor.statusWindow.length) * 100; + + // If threshold has been met and the monitor is not already down, mark down: + if (failureRate >= monitor.statusWindowThreshold && monitor.status !== false) { + newStatus = false; + statusChanged = true; + } + // If the failure rate is below the threshold and the monitor is down, recover: + else if (failureRate < monitor.statusWindowThreshold && monitor.status === false) { + newStatus = true; + statusChanged = true; + } + + monitor.status = newStatus; + const updated = await this.monitorsRepository.updateById(monitor.id, monitor.teamId, monitor); + + return { + monitor: updated, + statusChanged, + prevStatus, + code, + timestamp: new Date().getTime(), + }; + } catch (error: any) { + error.service = SERVICE_NAME; + error.method = "updateStatus"; + throw error; + } + }; + + insertCheck = async (check: Check) => { + try { + if (typeof check === "undefined") { + this.logger.warn({ + message: "Failed to build check", + service: SERVICE_NAME, + method: "insertCheck", + }); + return false; + } + this.buffer.addToBuffer({ check }); + return true; + } catch (error: any) { + this.logger.error({ + message: error.message, + service: error.service || SERVICE_NAME, + method: error.method || "insertCheck", + details: error.details || `Error inserting check for monitor: ${check?.metadata.monitorId}`, + stack: error.stack, + }); + } + }; +} diff --git a/server/src/service/system/settingsService.js b/server/src/service/system/settingsService.js index 70d8d192c..cea46f7ed 100755 --- a/server/src/service/system/settingsService.js +++ b/server/src/service/system/settingsService.js @@ -60,6 +60,7 @@ class SettingsService { await this.AppSettings.create({}); settings = await this.AppSettings.findOne({ singleton: true }).select("-__v -_id -createdAt -updatedAt -singleton").lean(); } + return settings; } } diff --git a/server/src/types/alert.ts b/server/src/types/alert.ts new file mode 100644 index 000000000..4725ebee8 --- /dev/null +++ b/server/src/types/alert.ts @@ -0,0 +1,29 @@ +import { NotificationChannel } from "@/types/index.js"; +export interface AlertWebhookPayload { + body: Record; +} + +export interface AlertPagerDutyPayload { + routingKey: string; + monitorUrl?: string; +} + +export interface AlertMatrixPayload { + friendlyName?: string; + homeserverUrl: string; + accessToken: string; + roomId: string; + monitorName: string; +} + +export interface Alert { + channel: NotificationChannel; + address?: string; + subject: string; + message: string; + html?: string; + discordContent?: Record | null; + webhook?: AlertWebhookPayload | null; + pagerDuty?: AlertPagerDutyPayload | null; + matrix?: AlertMatrixPayload | null; +} diff --git a/server/src/types/check.ts b/server/src/types/check.ts index 28353497e..f8ee4f618 100644 --- a/server/src/types/check.ts +++ b/server/src/types/check.ts @@ -1,4 +1,6 @@ import type { MonitorType } from "@/types/index.js"; +import type { Response } from "got"; +export type GotTimings = Response["timings"]; export interface CheckMetadata { monitorId: string; @@ -6,64 +8,41 @@ export interface CheckMetadata { type: MonitorType; } -export interface CheckTimingPhases { - wait: number; - dns: number; - tcp: number; - tls: number; - request: number; - firstByte: number; - download: number; - total: number; -} - -export interface CheckTimings { - start: number; - socket: number; - lookup: number; - connect: number; - secureConnect: number; - upload: number; - response: number; - end: number; - phases: CheckTimingPhases; -} - export interface CheckCpuInfo { - physical_core: number; - logical_core: number; - frequency: number; - temperature: number[]; - free_percent: number; - usage_percent: number; + physical_core?: number; + logical_core?: number; + frequency?: number; + temperature?: number[]; + free_percent?: number; + usage_percent?: number; } export interface CheckMemoryInfo { - total_bytes: number; - available_bytes: number; - used_bytes: number; - usage_percent: number; + total_bytes?: number; + available_bytes?: number; + used_bytes?: number; + usage_percent?: number; } export interface CheckHostInfo { - os: string; - platform: string; - kernel_version: string; + os?: string; + platform?: string; + kernel_version?: string; } export interface CheckCaptureInfo { - version: string; - mode: string; + version?: string; + mode?: string; } export interface CheckDiskInfo { - device: string; - mountpoint: string; - read_speed_bytes: number; - write_speed_bytes: number; - total_bytes: number; - free_bytes: number; - usage_percent: number; + device?: string; + mountpoint?: string; + read_speed_bytes?: number; + write_speed_bytes?: number; + total_bytes?: number; + free_bytes?: number; + usage_percent?: number; } export interface CheckErrorInfo { @@ -86,11 +65,11 @@ export interface CheckNetworkInterfaceInfo { } export interface CheckAudits { - cls: ILighthouseAudit; - si: ILighthouseAudit; - fcp: ILighthouseAudit; - lcp: ILighthouseAudit; - tbt: ILighthouseAudit; + cls?: ILighthouseAudit; + si?: ILighthouseAudit; + fcp?: ILighthouseAudit; + lcp?: ILighthouseAudit; + tbt?: ILighthouseAudit; } export interface ILighthouseAudit { @@ -107,19 +86,19 @@ export interface Check { metadata: CheckMetadata; status: boolean; responseTime: number; - timings: CheckTimings; + timings?: GotTimings; statusCode: number; message: string; ack: boolean; ackAt?: string | null; expiry: string; - cpu: CheckCpuInfo; - memory: CheckMemoryInfo; - disk: CheckDiskInfo[]; - host: CheckHostInfo; - errors: CheckErrorInfo[]; - capture: CheckCaptureInfo; - net: CheckNetworkInterfaceInfo[]; + cpu?: CheckCpuInfo; + memory?: CheckMemoryInfo; + disk?: CheckDiskInfo[]; + host?: CheckHostInfo; + errors?: CheckErrorInfo[]; + capture?: CheckCaptureInfo; + net?: CheckNetworkInterfaceInfo[]; accessibility?: number; bestPractices?: number; seo?: number; @@ -129,3 +108,66 @@ export interface Check { createdAt: string; updatedAt: string; } +export interface ChecksQueryResult { + checksCount: number; + checks: Check[]; +} + +export interface PageSpeedChecksResult { + monitorType: "pagespeed"; + checks: Check[]; +} + +export interface HardwareChecksResult { + monitorType: "hardware"; + aggregateData: { + latestCheck: Check | null; + totalChecks: number; + }; + upChecks: { + totalChecks: number; + }; + checks: Array<{ + _id: string; + avgCpuUsage: number; + avgMemoryUsage: number; + avgTemperature: number[]; + disks: Array<{ + name: string; + readSpeed: number; + writeSpeed: number; + totalBytes: number; + freeBytes: number; + usagePercent: number; + }>; + net: Array<{ + name: string; + bytesSentPerSecond: number; + deltaBytesRecv: number; + deltaPacketsSent: number; + deltaPacketsRecv: number; + deltaErrIn: number; + deltaErrOut: number; + deltaDropIn: number; + deltaDropOut: number; + deltaFifoIn: number; + deltaFifoOut: number; + }>; + }>; +} + +export interface UptimeChecksResult { + monitorType: Exclude; + groupedChecks: Array<{ _id: string; avgResponseTime: number; totalChecks: number }>; + groupedUpChecks: Array<{ _id: string; totalChecks: number; avgResponseTime: number }>; + groupedDownChecks: Array<{ _id: string; totalChecks: number; avgResponseTime: number }>; + uptimePercentage: number; + avgResponseTime: number; +} + +export interface ChecksSummary { + totalChecks: number; + resolvedChecks: number; + downChecks: number; + cannotResolveChecks: number; +} diff --git a/server/src/types/email.ts b/server/src/types/email.ts new file mode 100644 index 000000000..2ffae187b --- /dev/null +++ b/server/src/types/email.ts @@ -0,0 +1,17 @@ +import { Settings } from "./settings.js"; + +export type EmailTransportConfig = Pick< + Settings, + | "systemEmailHost" + | "systemEmailPort" + | "systemEmailAddress" + | "systemEmailPassword" + | "systemEmailUser" + | "systemEmailConnectionHost" + | "systemEmailTLSServername" + | "systemEmailSecure" + | "systemEmailPool" + | "systemEmailIgnoreTLS" + | "systemEmailRequireTLS" + | "systemEmailRejectUnauthorized" +>; diff --git a/server/src/types/express.d.ts b/server/src/types/express.d.ts index b9f7386f6..66755659c 100644 --- a/server/src/types/express.d.ts +++ b/server/src/types/express.d.ts @@ -1,10 +1,10 @@ -import { ITokenizedUser } from "../db/models/index.ts"; +import type { User } from "@/types/index.js"; declare global { namespace Express { interface Request { file?: Multer.File; - user?: ITokenizedUser; + user?: User | undefined; resource?: any; } } diff --git a/server/src/types/incident.ts b/server/src/types/incident.ts new file mode 100644 index 000000000..39dfb3d0d --- /dev/null +++ b/server/src/types/incident.ts @@ -0,0 +1,49 @@ +// export type IncidentResolutionType = "automatic" | "manual" | null; + +export const IncidentResolutionTypes = ["automatic", "manual", null] as const; +export type IncidentResolutionType = (typeof IncidentResolutionTypes)[number]; + +export interface Incident { + id: string; + monitorId: string; + teamId: string; + startTime: string; + endTime: string | null; + status: boolean; + message?: string | null; + statusCode?: number | null; + resolutionType: IncidentResolutionType; + resolvedBy?: string | null; + comment?: string | null; + createdAt: string; + updatedAt: string; +} + +export interface IncidentSummaryTopMonitor { + monitorId: string; + monitorName: string | null; + incidentCount: number; +} + +export interface IncidentSummaryItem { + id: string; + monitorId: string; + monitorName: string | null; + status: boolean; + startTime: string; + endTime: string | null; + resolutionType: IncidentResolutionType; + message: string | null; + statusCode: number | null; + createdAt: string; +} + +export interface IncidentSummary { + total: number; + totalActive: number; + totalManualResolutions: number; + totalAutomaticResolutions: number; + avgResolutionTimeHours: number; + topMonitor: IncidentSummaryTopMonitor | null; + latestIncidents: IncidentSummaryItem[]; +} diff --git a/server/src/types/index.ts b/server/src/types/index.ts index 2367f1c1c..b0b6b07c5 100644 --- a/server/src/types/index.ts +++ b/server/src/types/index.ts @@ -1,3 +1,13 @@ export * from "@/types/check.js"; export * from "@/types/monitor.js"; export * from "@/types/monitorStats.js"; +export * from "@/types/statusPage.js"; +export * from "@/types/network.js"; +export * from "@/types/user.js"; +export * from "@/types/invite.js"; +export * from "@/types/recoveryToken.js"; +export * from "@/types/settings.js"; +export * from "@/types/notification.js"; +export * from "@/types/alert.js"; +export * from "@/types/incident.js"; +export * from "@/types/email.js"; diff --git a/server/src/types/invite.ts b/server/src/types/invite.ts new file mode 100644 index 000000000..cdbdb37e5 --- /dev/null +++ b/server/src/types/invite.ts @@ -0,0 +1,12 @@ +import type { UserRole } from "@/types/user.js"; + +export interface Invite { + id: string; + email: string; + teamId: string; + role: UserRole[]; + token: string; + expiry: string; + createdAt: string; + updatedAt: string; +} diff --git a/server/src/types/monitor.ts b/server/src/types/monitor.ts index 4c8dc7528..dc3bd8c09 100644 --- a/server/src/types/monitor.ts +++ b/server/src/types/monitor.ts @@ -1,4 +1,4 @@ -export const MonitorTypes = ["http", "ping", "pagespeed", "hardware", "docker", "port", "game"] as const; +export const MonitorTypes = ["http", "ping", "pagespeed", "hardware", "docker", "port", "game", "unknown"] as const; export type MonitorType = (typeof MonitorTypes)[number]; export interface MonitorThresholds { diff --git a/server/src/types/network.ts b/server/src/types/network.ts new file mode 100644 index 000000000..6bed40316 --- /dev/null +++ b/server/src/types/network.ts @@ -0,0 +1,112 @@ +import type { + CheckCaptureInfo, + CheckCpuInfo, + CheckDiskInfo, + CheckErrorInfo, + CheckHostInfo, + CheckMemoryInfo, + CheckNetworkInterfaceInfo, + GotTimings, + ILighthouseAudit, + Monitor, + MonitorMatchMethod, + MonitorType, +} from "@/types/index.js"; + +export interface MonitorStatusResponse { + monitorId: string; + teamId: string; + type: MonitorType; + status: boolean; + code: number; + message: string; + responseTime?: number; + payload?: T | null; + timings?: GotTimings; + first_byte_took?: number; + body_read_took?: number; + dns_took?: number; + conn_took?: number; + connect_took?: number; + tls_took?: number; + jsonPath?: string; + matchMethod?: MonitorMatchMethod; + expectedValue?: string; + extracted?: unknown; +} + +export interface PingStatusPayload { + host: string; + numeric_host?: string; + alive: boolean; + time: number; + times?: number[]; + output?: string; + min?: string; + max?: string; + avg?: string; + stddev?: string; + packetLoss?: string; +} + +export type HttpStatusPayload = unknown; + +export interface PageSpeedCategoryScore { + score?: number | null; +} + +export interface PageSpeedStatusPayload { + lighthouseResult?: { + categories?: { + accessibility?: PageSpeedCategoryScore; + "best-practices"?: PageSpeedCategoryScore; + performance?: PageSpeedCategoryScore; + seo?: PageSpeedCategoryScore; + [key: string]: PageSpeedCategoryScore | undefined; + }; + audits?: Record; + }; + [key: string]: unknown; +} + +export interface HardwareStatusMetrics { + cpu?: CheckCpuInfo; + memory?: CheckMemoryInfo; + disk?: CheckDiskInfo[]; + host?: CheckHostInfo; + net?: CheckNetworkInterfaceInfo[]; +} + +export interface HardwareStatusPayload { + data?: HardwareStatusMetrics; + errors?: CheckErrorInfo[] | { errors?: CheckErrorInfo[] }; + capture?: CheckCaptureInfo; + [key: string]: unknown; +} + +export type DockerStatusPayload = Record; + +export interface PortStatusPayload { + success: boolean; +} + +export type GameStatusPayload = Record; + +export interface MonitorPayloadMap { + ping: PingStatusPayload; + http: HttpStatusPayload; + pagespeed: PageSpeedStatusPayload; + hardware: HardwareStatusPayload; + docker: DockerStatusPayload; + port: PortStatusPayload; + game: GameStatusPayload; + default: unknown; +} + +export type StatusChangeResult = { + monitor: Monitor; + statusChanged: boolean; + prevStatus: boolean | undefined; + code: number; + timestamp: number; +}; diff --git a/server/src/types/notification.ts b/server/src/types/notification.ts new file mode 100644 index 000000000..669c840ca --- /dev/null +++ b/server/src/types/notification.ts @@ -0,0 +1,17 @@ +export const NotificationChannels = ["email", "slack", "discord", "webhook", "pager_duty", "matrix"] as const; +export type NotificationChannel = (typeof NotificationChannels)[number]; + +export interface Notification { + id: string; + userId: string; + teamId: string; + type: NotificationChannel; + notificationName: string; + address?: string; + phone?: string; + homeserverUrl?: string; + roomId?: string; + accessToken?: string; + createdAt: string; + updatedAt: string; +} diff --git a/server/src/types/recoveryToken.ts b/server/src/types/recoveryToken.ts new file mode 100644 index 000000000..488e1f4c1 --- /dev/null +++ b/server/src/types/recoveryToken.ts @@ -0,0 +1,8 @@ +export interface RecoveryToken { + id: string; + email: string; + token: string; + expiry: string; + createdAt: string; + updatedAt: string; +} diff --git a/server/src/types/settings.ts b/server/src/types/settings.ts new file mode 100644 index 000000000..108cdcb72 --- /dev/null +++ b/server/src/types/settings.ts @@ -0,0 +1,32 @@ +export interface SettingsThresholds { + cpu?: number; + memory?: number; + disk?: number; + temperature?: number; +} + +export interface Settings { + id: string; + checkTTL: number; + language: string; + jwtSecret?: string; + pagespeedApiKey?: string; + systemEmailHost?: string; + systemEmailPort?: number; + systemEmailAddress?: string; + systemEmailPassword?: string; + systemEmailUser?: string; + systemEmailConnectionHost?: string; + systemEmailTLSServername?: string; + systemEmailSecure: boolean; + systemEmailPool: boolean; + systemEmailIgnoreTLS: boolean; + systemEmailRequireTLS: boolean; + systemEmailRejectUnauthorized: boolean; + showURL: boolean; + singleton: boolean; + version: number; + globalThresholds?: SettingsThresholds; + createdAt: string; + updatedAt: string; +} diff --git a/server/src/types/statusPage.ts b/server/src/types/statusPage.ts new file mode 100644 index 000000000..64a5ac50b --- /dev/null +++ b/server/src/types/statusPage.ts @@ -0,0 +1,29 @@ +export const StatusPageTypes = ["uptime"] as const; +export type StatusPageType = (typeof StatusPageTypes)[number]; + +export interface StatusPageLogo { + data: Buffer; + contentType: string; +} + +export interface StatusPage { + id: string; + userId: string; + teamId: string; + type: StatusPageType; + companyName: string; + url: string; + timezone?: string; + color: string; + monitors: string[]; + subMonitors: string[]; + originalMonitors?: string[]; + logo?: StatusPageLogo | null; + isPublished: boolean; + showCharts: boolean; + showUptimePercentage: boolean; + showAdminLoginLink: boolean; + customCSS: string; + createdAt: string; + updatedAt: string; +} diff --git a/server/src/types/user.ts b/server/src/types/user.ts new file mode 100644 index 000000000..41c009791 --- /dev/null +++ b/server/src/types/user.ts @@ -0,0 +1,24 @@ +export const UserRoles = ["user", "admin", "superadmin", "demo"] as const; +export type UserRole = (typeof UserRoles)[number]; + +export interface UserProfileImage { + data?: Buffer; + contentType?: string; +} + +export interface User { + id: string; + firstName: string; + lastName: string; + email: string; + password: string; + avatarImage?: string; + profileImage?: UserProfileImage; + isActive: boolean; + isVerified: boolean; + role: UserRole[]; + teamId: string; + checkTTL?: number; + createdAt: string; + updatedAt: string; +} diff --git a/server/src/utils/utils.js b/server/src/utils/utils.ts similarity index 65% rename from server/src/utils/utils.js rename to server/src/utils/utils.ts index bcb4d8e5e..a82d8734f 100755 --- a/server/src/utils/utils.js +++ b/server/src/utils/utils.ts @@ -1,9 +1,4 @@ -/** - * Converts a request body parameter to a boolean. - * @param {string | boolean} value - * @returns {boolean} - */ -const ParseBoolean = (value) => { +export const ParseBoolean = (value: boolean | string | null | undefined) => { if (value === true || value === "true") { return true; } else if (value === false || value === "false" || value === null || value === undefined) { @@ -11,7 +6,7 @@ const ParseBoolean = (value) => { } }; -const getTokenFromHeaders = (headers) => { +export const getTokenFromHeaders = (headers: Record) => { const authorizationHeader = headers.authorization; if (!authorizationHeader) throw new Error("No auth headers"); @@ -20,5 +15,3 @@ const getTokenFromHeaders = (headers) => { return parts[1]; }; - -export { ParseBoolean, getTokenFromHeaders }; diff --git a/server/src/validation/joi.js b/server/src/validation/joi.js index c09ac88b9..8533b4e44 100755 --- a/server/src/validation/joi.js +++ b/server/src/validation/joi.js @@ -17,8 +17,7 @@ const roleValidatior = (role) => (value, helpers) => { // Auth //**************************************** -const passwordPattern = - /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!?@#$%^&*()\-_=+[\]{};:'",.<>~`|\\/])[A-Za-z0-9!?@#$%^&*()\-_=+[\]{};:'",.<>~`|\\/]+$/; +const passwordPattern = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!?@#$%^&*()\-_=+[\]{};:'",.~`|\\/])[A-Za-z0-9!?@#$%^&*()\-_=+[\]{};:'",.~`|\\/]+$/; const loginValidation = joi.object({ email: joi.string().email().required().lowercase(), @@ -413,7 +412,7 @@ const updateAppSettingsBodyValidation = joi.object({ pagespeedApiKey: joi.string().allow(""), language: joi.string().allow(""), timezone: joi.string().allow(""), - // showURL: joi.bool().required(), + showURL: joi.bool().optional(), systemEmailHost: joi.string().allow(""), systemEmailPort: joi.number().allow(""), systemEmailAddress: joi.string().allow(""), diff --git a/server/test/monitorService.test.ts b/server/test/monitorService.test.ts index 7a3bbe12f..32708a42e 100644 --- a/server/test/monitorService.test.ts +++ b/server/test/monitorService.test.ts @@ -1,12 +1,14 @@ import { jest } from "@jest/globals"; import { MonitorService } from "../src/service/business/monitorService.ts"; -import type { IMonitorsRepository, IChecksRepository } from "../src/repositories/index.ts"; +import type { IChecksRepository, IMonitorStatsRepository, IMonitorsRepository, IStatusPagesRepository } from "../src/repositories/index.ts"; const createMonitorsRepositoryMock = () => ({ findMonitorCountByTeamIdAndType: jest.fn(), findByTeamId: jest.fn(), findById: jest.fn(), + findMonitorsSummaryByTeamId: jest.fn(), + findGroupsByTeamId: jest.fn(), create: jest.fn(), createBulkMonitors: jest.fn(), deleteByTeamId: jest.fn(), @@ -18,32 +20,34 @@ const createChecksRepositoryMock = () => findDateRangeChecksByMonitor: jest.fn(), }) as unknown as IChecksRepository; +const createMonitorStatsRepositoryMock = () => + ({ + findByMonitorId: jest.fn(), + deleteByMonitorId: jest.fn(), + }) as unknown as IMonitorStatsRepository; + +const createStatusPagesRepositoryMock = () => + ({ + removeMonitorFromStatusPages: jest.fn(), + }) as unknown as IStatusPagesRepository; + const createService = ({ monitorsRepository = createMonitorsRepositoryMock(), checksRepository = createChecksRepositoryMock(), - monitorStatsRepository = { findByMonitorId: jest.fn() }, - monitorModuleOverrides = {}, + monitorStatsRepository = createMonitorStatsRepositoryMock(), + statusPagesRepository = createStatusPagesRepositoryMock(), }: { monitorsRepository?: IMonitorsRepository; checksRepository?: IChecksRepository; - monitorStatsRepository?: { findByMonitorId: jest.Mock }; - monitorModuleOverrides?: Record; + monitorStatsRepository?: IMonitorStatsRepository; + statusPagesRepository?: IStatusPagesRepository; } = {}) => { - const monitorModule = { - getMonitorById: jest.fn().mockResolvedValue({ teamId: { equals: () => true } }), - getMonitorStatsById: jest.fn().mockResolvedValue({ latest: {} }), - getMonitorsByTeamId: jest.fn().mockResolvedValue([]), - getMonitorsAndSummaryByTeamId: jest.fn().mockResolvedValue({ monitors: [], summary: {} }), - ...monitorModuleOverrides, - }; - return new MonitorService({ db: { - monitorModule, - statusPageModule: { deleteStatusPagesByMonitorId: jest.fn() }, checkModule: { deleteChecks: jest.fn() }, + statusPageModule: { deleteStatusPagesByMonitorId: jest.fn() }, pageSpeedCheckModule: { deletePageSpeedChecksByMonitorId: jest.fn() }, - notificationsModule: { deleteNotificationsByMonitorId: jest.fn() }, + notificationModule: { deleteNotificationsByMonitorId: jest.fn() }, }, jobQueue: { addJob: jest.fn(), @@ -66,6 +70,7 @@ const createService = ({ monitorsRepository, checksRepository, monitorStatsRepository, + statusPagesRepository, }); }; @@ -106,29 +111,41 @@ describe("MonitorService", () => { }); describe("getMonitorsByTeamId", () => { - it("returns monitors array from db module", async () => { - const monitorsPayload = [ + it("returns monitors array from repository", async () => { + const monitorsRepository = createMonitorsRepositoryMock(); + (monitorsRepository.findByTeamId as jest.Mock).mockResolvedValue([ { id: "m1", name: "Monitor 1" }, { id: "m2", name: "Monitor 2" }, - ]; - const monitorModuleOverrides = { - getMonitorsByTeamId: jest.fn().mockResolvedValue(monitorsPayload), - }; - const service = createService({ monitorModuleOverrides }); + ]); + const service = createService({ monitorsRepository }); const result = await service.getMonitorsByTeamId({ teamId: "team" } as any); expect(result).toHaveLength(2); expect(result[0]).toHaveProperty("id", "m1"); }); }); - describe("getMonitorsAndSummaryByTeamId", () => { - it("returns monitors with summary block", async () => { - const monitorModuleOverrides = { - getMonitorsAndSummaryByTeamId: jest.fn().mockResolvedValue({ monitors: [{ id: "m1" }], summary: { total: 1, uptime: 0.99 } }), - }; - const service = createService({ monitorModuleOverrides }); - const result = await service.getMonitorsAndSummaryByTeamId({ teamId: "team" }); - expect(result).toEqual({ monitors: [{ id: "m1" }], summary: { total: 1, uptime: 0.99 } }); + describe("getMonitorsWithChecksByTeamId summary", () => { + it("includes summary and monitors with checks", async () => { + const monitorsRepository = createMonitorsRepositoryMock(); + (monitorsRepository.findMonitorCountByTeamIdAndType as jest.Mock).mockResolvedValue(1); + (monitorsRepository.findByTeamId as jest.Mock).mockResolvedValue([{ id: "m1", type: "http" }]); + (monitorsRepository.findMonitorsSummaryByTeamId as jest.Mock).mockResolvedValue({ + totalMonitors: 1, + upMonitors: 1, + downMonitors: 0, + pausedMonitors: 0, + }); + + const checksRepository = createChecksRepositoryMock(); + (checksRepository.findLatestChecksByMonitorIds as jest.Mock).mockResolvedValue({ m1: [] }); + + const service = createService({ monitorsRepository, checksRepository }); + const result = await service.getMonitorsWithChecksByTeamId({ teamId: "team" }); + expect(result).toEqual({ + summary: { totalMonitors: 1, upMonitors: 1, downMonitors: 0, pausedMonitors: 0 }, + count: 1, + monitors: [{ id: "m1", type: "http", checks: [] }], + }); }); }); @@ -163,7 +180,7 @@ describe("MonitorService", () => { (monitorsRepository.findById as jest.Mock).mockResolvedValue(monitor); const checksRepository = createChecksRepositoryMock(); (checksRepository.findDateRangeChecksByMonitor as jest.Mock).mockResolvedValue({ - monitorType: "uptime", + monitorType: "http", groupedChecks: [{ _id: "2024-01-01", avgResponseTime: 100, totalChecks: 2 }], groupedUpChecks: [{ _id: "2024-01-01", totalChecks: 2, avgResponseTime: 90 }], groupedDownChecks: [{ _id: "2024-01-01", totalChecks: 0, avgResponseTime: 0 }], @@ -171,27 +188,23 @@ describe("MonitorService", () => { avgResponseTime: 95, }); - const monitorStatsRepository = { - findByMonitorId: jest.fn().mockResolvedValue({ - id: "stats-1", - monitorId: monitor.id, - avgResponseTime: 90, - totalChecks: 10, - totalUpChecks: 9, - totalDownChecks: 1, - uptimePercentage: 0.9, - lastCheckTimestamp: 123456789, - lastResponseTime: 80, - timeOfLastFailure: 123456700, - createdAt: new Date().toISOString(), - updatedAt: new Date().toISOString(), - }), - } as any; - const monitorModuleOverrides = { - getMonitorById: jest.fn().mockResolvedValue({ teamId: { equals: (value: string) => value === TEAM_ID } }), - }; + const monitorStatsRepository = createMonitorStatsRepositoryMock(); + (monitorStatsRepository.findByMonitorId as jest.Mock).mockResolvedValue({ + id: "stats-1", + monitorId: monitor.id, + avgResponseTime: 90, + totalChecks: 10, + totalUpChecks: 9, + totalDownChecks: 1, + uptimePercentage: 0.9, + lastCheckTimestamp: 123456789, + lastResponseTime: 80, + timeOfLastFailure: 123456700, + createdAt: new Date().toISOString(), + updatedAt: new Date().toISOString(), + }); - const service = createService({ monitorsRepository, checksRepository, monitorModuleOverrides, monitorStatsRepository }); + const service = createService({ monitorsRepository, checksRepository, monitorStatsRepository }); const result = await service.getUptimeDetailsById({ teamId: TEAM_ID, monitorId: "monitor-1", dateRange: "recent" }); expect(result).toHaveProperty("monitorData"); diff --git a/server/test/superSimpleQueueHelper.test.ts b/server/test/superSimpleQueueHelper.test.ts new file mode 100644 index 000000000..19caef876 --- /dev/null +++ b/server/test/superSimpleQueueHelper.test.ts @@ -0,0 +1,102 @@ +import { describe, expect, it, jest } from "@jest/globals"; +import SuperSimpleQueueHelper from "../src/service/infrastructure/SuperSimpleQueue/SuperSimpleQueueHelper.ts"; +import type { Monitor } from "../src/types/monitor.ts"; + +const createLogger = () => ({ info: jest.fn(), error: jest.fn(), warn: jest.fn(), debug: jest.fn() }); + +const createHelper = (overrides?: Partial[0]>) => { + const maintenanceWindowModule = { + getMaintenanceWindowsByMonitorId: jest.fn().mockResolvedValue([]), + }; + const statusServiceMock = { + updateMonitorStatus: jest.fn().mockResolvedValue({ monitor: { id: "m1" }, statusChanged: true, prevStatus: false }), + }; + const helper = new SuperSimpleQueueHelper({ + db: { maintenanceWindowModule }, + logger: createLogger(), + networkService: { requestStatus: jest.fn() }, + statusService: statusServiceMock, + notificationService: { handleNotifications: jest.fn().mockResolvedValue(undefined) }, + ...overrides, + }); + return { helper, maintenanceWindowModule }; +}; + +describe("SuperSimpleQueueHelper", () => { + describe("getMonitorJob", () => { + it("skips execution when monitor is in maintenance window", async () => { + const { helper } = createHelper(); + const spy = jest.spyOn(helper, "isInMaintenanceWindow").mockResolvedValue(true); + const job = helper.getMonitorJob(); + await job({ id: "m1", teamId: "team", interval: 60000 } as Monitor); + expect(helper["networkService"].requestStatus).not.toHaveBeenCalled(); + expect(helper["logger"].debug).toHaveBeenCalledWith( + expect.objectContaining({ message: expect.stringContaining("Monitor m1 is in maintenance window") }) + ); + spy.mockRestore(); + }); + + it("processes monitor status and notifications when active", async () => { + const networkResponse = { monitor: { id: "m1" }, status: true }; + const updatedMonitor = { id: "m1", status: true }; + const { helper } = createHelper({ + networkService: { requestStatus: jest.fn().mockResolvedValue(networkResponse) }, + statusService: { + updateMonitorStatus: jest.fn().mockResolvedValue({ monitor: updatedMonitor, statusChanged: true, prevStatus: false }), + }, + notificationService: { handleNotifications: jest.fn().mockResolvedValue(undefined) }, + }); + jest.spyOn(helper, "isInMaintenanceWindow").mockResolvedValue(false); + const job = helper.getMonitorJob(); + const monitor = { id: "m1", teamId: "team" } as Monitor; + await job(monitor); + expect(helper["networkService"].requestStatus).toHaveBeenCalledWith(monitor); + expect(helper["statusService"].updateMonitorStatus).toHaveBeenCalledWith(networkResponse); + expect(helper["notificationService"].handleNotifications).toHaveBeenCalledWith( + expect.objectContaining({ monitor: updatedMonitor, statusChanged: true, prevStatus: false }) + ); + }); + + it("throws when monitor id is missing", async () => { + const { helper } = createHelper(); + const job = helper.getMonitorJob(); + await expect(job({} as Monitor)).rejects.toThrow("No monitor id"); + expect(helper["logger"].warn).toHaveBeenCalled(); + }); + }); + + describe("isInMaintenanceWindow", () => { + it("returns true when an active window spans now", async () => { + const now = new Date(); + const { helper, maintenanceWindowModule } = createHelper(); + maintenanceWindowModule.getMaintenanceWindowsByMonitorId.mockResolvedValue([ + { + active: true, + start: new Date(now.getTime() - 1000).toISOString(), + end: new Date(now.getTime() + 1000).toISOString(), + repeat: 0, + }, + ]); + await expect(helper.isInMaintenanceWindow("m1", "team")).resolves.toBe(true); + }); + + it("returns true when repeat interval advances window into current time", async () => { + const now = Date.now(); + const { helper, maintenanceWindowModule } = createHelper(); + maintenanceWindowModule.getMaintenanceWindowsByMonitorId.mockResolvedValue([ + { + active: true, + start: new Date(now - 7200000).toISOString(), + end: new Date(now - 6600000).toISOString(), + repeat: 3600000, + }, + ]); + await expect(helper.isInMaintenanceWindow("m1", "team")).resolves.toBe(true); + }); + + it("returns false when no active windows exist", async () => { + const { helper } = createHelper(); + await expect(helper.isInMaintenanceWindow("m1", "team")).resolves.toBe(false); + }); + }); +}); diff --git a/server/tsconfig.jest.json b/server/tsconfig.jest.json index 928b0977c..80c321cf6 100644 --- a/server/tsconfig.jest.json +++ b/server/tsconfig.jest.json @@ -3,7 +3,8 @@ "compilerOptions": { "rootDir": ".", "types": ["jest"], - "noEmit": true + "noEmit": true, + "resolveJsonModule": true }, "include": ["src", "test"] } diff --git a/server/tsconfig.json b/server/tsconfig.json index cbb874656..bdb3a7b0e 100644 --- a/server/tsconfig.json +++ b/server/tsconfig.json @@ -4,7 +4,7 @@ "allowJs": true, "checkJs": false, "paths": { - "@/*": ["./src/*"] // allows "@/db" -> "./src/db" + "@/*": ["./src/*"] }, "outDir": "./dist", "strict": true,