File size: 1,300 Bytes
c63e174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const db = require('../config/db');

const DEFAULT_ONLINE_STALE_SECONDS = 120;

function getOnlineStaleSeconds() {
  const configured = Number(process.env.DEVICE_ONLINE_STALE_SECONDS);
  return Number.isFinite(configured) && configured > 0
    ? Math.floor(configured)
    : DEFAULT_ONLINE_STALE_SECONDS;
}

async function markStaleOnlineDevicesOffline(context = 'deviceStatus') {
  const staleSeconds = getOnlineStaleSeconds();

  await db.query(
    `INSERT INTO device_status_log (device_id, old_status, new_status)
     SELECT id, status, 'offline'
     FROM devices
     WHERE status = 'online'
       AND billing_status != 'cancelled'
       AND (last_seen_at IS NULL OR TIMESTAMPDIFF(SECOND, last_seen_at, NOW()) > ?)`,
    [staleSeconds],
  );

  const result = await db.query(
    `UPDATE devices
     SET status = 'offline'
     WHERE status = 'online'
       AND billing_status != 'cancelled'
       AND (last_seen_at IS NULL OR TIMESTAMPDIFF(SECOND, last_seen_at, NOW()) > ?)`,
    [staleSeconds],
  );

  const changed = result.affectedRows || 0;
  if (changed > 0) {
    console.log(`[${context}] Marked ${changed} stale online device(s) offline`);
  }
  return changed;
}

module.exports = {
  DEFAULT_ONLINE_STALE_SECONDS,
  getOnlineStaleSeconds,
  markStaleOnlineDevicesOffline,
};