All files / src/routes/api/v1 monitors.js

0% Statements 0/77
0% Branches 0/44
0% Functions 0/8
0% Lines 0/76

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209                                                                                                                                                                                                                                                                                                                                                                                                                                 
/**
 * API v1 — Uptime Monitors (read-only)
 *
 * GET /api/v1/monitors            — Liste des monitors
 * GET /api/v1/monitors/:id        — Detail d'un monitor
 * GET /api/v1/monitors/:id/history — Historique des checks
 *
 * @module routes/api/v1/monitors
 */
 
const express = require('express');
const { pool: db } = require('../../../db');
const { requireScope } = require('../../../middleware/apiAuth');
const { checkQuota, checkPlanValue } = require('../../../middleware/planLimits');
const { validatePublicUrl } = require('../../../utils/networkValidator');
const { apiSuccess, apiPaginated, apiError, parsePagination, makeApiDeleteHandler } = require('../../../helpers/apiResponse');
 
const router = express.Router();
 
const HISTORY_RANGES = { '1h': '1 hour', '6h': '6 hours', '24h': '24 hours', '7d': '7 days', '30d': '30 days' };
 
/** Colonnes SQL enrichies pour un monitor (dernier statut, latence, uptime). */
const MONITOR_STATS_COLUMNS = `
  m.id, m.url, m.label, m.interval_s, m.enabled, m.created_at,
  (SELECT status FROM uptime_history WHERE monitor_id = m.id ORDER BY created_at DESC LIMIT 1) AS last_status,
  (SELECT latency_ms FROM uptime_history WHERE monitor_id = m.id ORDER BY created_at DESC LIMIT 1) AS last_latency,
  (SELECT ROUND(
    COUNT(*) FILTER (WHERE status BETWEEN 200 AND 399) * 100.0 / GREATEST(COUNT(*), 1), 1
  ) FROM uptime_history WHERE monitor_id = m.id AND created_at > NOW() - INTERVAL '24 hours') AS uptime_24h,
  (SELECT ROUND(
    COUNT(*) FILTER (WHERE status BETWEEN 200 AND 399) * 100.0 / GREATEST(COUNT(*), 1), 1
  ) FROM uptime_history WHERE monitor_id = m.id AND created_at > NOW() - INTERVAL '30 days') AS uptime_30d
`;
 
// ─── GET /monitors ──────────────────────────────────────────────────────────
 
router.get('/', requireScope('read'), async (req, res, next) => {
  try {
    const { page, perPage, offset } = parsePagination(req.query);
 
    const [{ rows }, { rows: countRows }] = await Promise.all([
      db.query(
        `SELECT ${MONITOR_STATS_COLUMNS}
         FROM uptime_monitors m
         WHERE m.user_id = $1
         ORDER BY m.created_at
         LIMIT $2 OFFSET $3`,
        [req.user.id, perPage, offset],
      ),
      db.query('SELECT COUNT(*) FROM uptime_monitors WHERE user_id = $1', [req.user.id]),
    ]);
 
    apiPaginated(res, rows, { page, per_page: perPage, total: Number.parseInt(countRows[0].count) });
  } catch (err) {
    next(err);
  }
});
 
// ─── GET /monitors/:id ──────────────────────────────────────────────────────
 
router.get('/:id', requireScope('read'), async (req, res, next) => {
  try {
    const { rows } = await db.query(
      `SELECT ${MONITOR_STATS_COLUMNS}
       FROM uptime_monitors m
       WHERE m.id = $1 AND m.user_id = $2`,
      [req.params.id, req.user.id],
    );
 
    if (rows.length === 0) {
      return apiError(res, 404, 'NOT_FOUND', 'Monitor introuvable.');
    }
    apiSuccess(res, rows[0]);
  } catch (err) {
    next(err);
  }
});
 
// ─── GET /monitors/:id/history ──────────────────────────────────────────────
 
router.get('/:id/history', requireScope('read'), async (req, res, next) => {
  try {
    const range = req.query.range || '24h';
    const interval = HISTORY_RANGES[range];
    if (!interval) {
      return apiError(res, 400, 'INVALID_RANGE', `Range invalide. Valeurs : ${Object.keys(HISTORY_RANGES).join(', ')}`);
    }
 
    // Verifier ownership
    const monitorCheck = await db.query(
      'SELECT id FROM uptime_monitors WHERE id = $1 AND user_id = $2',
      [req.params.id, req.user.id],
    );
    if (monitorCheck.rows.length === 0) {
      return apiError(res, 404, 'NOT_FOUND', 'Monitor introuvable.');
    }
 
    const { rows } = await db.query(
      `SELECT status, latency_ms, created_at
       FROM uptime_history
       WHERE monitor_id = $1 AND created_at > NOW() - INTERVAL '${interval}'
       ORDER BY created_at`,
      [req.params.id],
    );
 
    const okCount = rows.filter(r => r.status >= 200 && r.status < 400).length;
    const uptimePercent = rows.length > 0 ? Math.round(okCount / rows.length * 1000) / 10 : null;
    const avgLatency = rows.length > 0
      ? Math.round(rows.reduce((s, r) => s + (r.latency_ms || 0), 0) / rows.length)
      : null;
 
    apiSuccess(res, { range, count: rows.length, uptime_percent: uptimePercent, avg_latency: avgLatency, checks: rows });
  } catch (err) {
    next(err);
  }
});
 
// ─── POST /monitors ─────────────────────────────────────────────────────────
 
router.post('/', requireScope('write'), checkQuota('uptime_monitors', 'uptime_monitors'), checkPlanValue('uptime_interval_seconds'), async (req, res, next) => {
  try {
    const { url, label, interval_s } = req.body;
    if (!url || !label) {
      return apiError(res, 400, 'VALIDATION_ERROR', 'url et label sont requis.');
    }
    if (!/^https?:\/\/.+/.test(url)) {
      return apiError(res, 400, 'VALIDATION_ERROR', 'URL invalide (doit commencer par http:// ou https://).');
    }
 
    const urlCheck = await validatePublicUrl(url);
    if (!urlCheck.valid) {
      return apiError(res, 400, 'VALIDATION_ERROR', urlCheck.reason || 'URL non autorisee.');
    }
 
    const minInterval = req.planLimit?.uptime_interval_seconds || 300;
    const interval = Math.max(minInterval, Math.min(3600, Number.parseInt(interval_s) || 300));
 
    const { rows } = await db.query(
      `INSERT INTO uptime_monitors (user_id, url, label, interval_s)
       VALUES ($1, $2, $3, $4)
       RETURNING id, url, label, interval_s, enabled, created_at`,
      [req.user.id, url, label, interval],
    );
 
    apiSuccess(res, rows[0], 201);
  } catch (err) {
    next(err);
  }
});
 
// ─── PATCH /monitors/:id ────────────────────────────────────────────────────
 
router.patch('/:id', requireScope('write'), checkPlanValue('uptime_interval_seconds'), async (req, res, next) => {
  try {
    const { rows: existing } = await db.query(
      'SELECT * FROM uptime_monitors WHERE id = $1 AND user_id = $2',
      [req.params.id, req.user.id],
    );
    if (existing.length === 0) {
      return apiError(res, 404, 'NOT_FOUND', 'Monitor introuvable.');
    }
 
    const monitor = existing[0];
    const url = req.body.url ?? monitor.url;
    const label = req.body.label ?? monitor.label;
    const enabled = req.body.enabled ?? monitor.enabled;
    const minInterval = req.planLimit?.uptime_interval_seconds || 300;
    const interval_s = req.body.interval_s == null
      ? monitor.interval_s
      : Math.max(minInterval, Math.min(3600, Number.parseInt(req.body.interval_s)));
 
    const { rows } = await db.query(
      `UPDATE uptime_monitors SET url=$1, label=$2, interval_s=$3, enabled=$4
       WHERE id=$5 AND user_id=$6
       RETURNING id, url, label, interval_s, enabled, created_at`,
      [url, label, interval_s, enabled, req.params.id, req.user.id],
    );
 
    apiSuccess(res, rows[0]);
  } catch (err) {
    next(err);
  }
});
 
// ─── DELETE /monitors/:id ───────────────────────────────────────────────────
 
router.delete('/:id', requireScope('write'), makeApiDeleteHandler('uptime_monitors', 'Monitor introuvable.'));
 
// ─── POST /monitors/:id/pause ───────────────────────────────────────────────
 
router.post('/:id/pause', requireScope('write'), async (req, res, next) => {
  try {
    const { rows } = await db.query(
      `UPDATE uptime_monitors SET enabled = NOT enabled
       WHERE id = $1 AND user_id = $2
       RETURNING id, enabled`,
      [req.params.id, req.user.id],
    );
    if (rows.length === 0) {
      return apiError(res, 404, 'NOT_FOUND', 'Monitor introuvable.');
    }
    apiSuccess(res, rows[0]);
  } catch (err) {
    next(err);
  }
});
 
module.exports = router;