Research Labs

2026-09-17 20:38 UTCopen field data · live

cron/health_check.php

Snapshot 2026.09.17-a2894de (current) · 35 lines · 1,994 bytes · tree · plain text

SHA-256 3d95f0ba6d5dab78423f4680e9edc7e1bd8db71c683a8757ba5b0d5066058312
1<?php
2/* Run every 15-30 min by cron: php cron/health_check.php
3 Computes freshness per instrument, writes events on state change, emails admin (throttled). */
4require_once __DIR__.'/../inc/helpers.php';
5$insts=db()->query('SELECT * FROM instruments')->fetchAll();
6foreach($insts as $i){
7 $q=db()->prepare("SELECT MAX(r.ts) m FROM readings r JOIN streams s ON s.id=r.stream_id WHERE s.instrument_id=? AND r.is_placeholder=0");
8 $q->execute([$i['id']]); $last=$q->fetch()['m'];
9 $live=db()->prepare("SELECT COUNT(*) c FROM streams WHERE instrument_id=? AND mode='live'"); $live->execute([$i['id']]);
10 $isLive=$live->fetch()['c']>0;
11 if(!$isLive){ $new='pending'; }
12 else{
13 $age=$last?(time()-strtotime($last))/60:1e9;
14 $new = $age < max(90,$i['cadence_min']*2) ? 'ok' : ($age < $i['cadence_min']*6 ? 'late' : 'silent');
15 }
16 if($new!==$i['status']){
17 db()->prepare('UPDATE instruments SET status=? WHERE id=?')->execute([$new,$i['id']]);
18 $class = in_array($new,['late','silent']) ? ($new==='silent'?'fault':'gap') : ($i['status']!=='pending'?'recovery':'info');
19 db()->prepare('INSERT INTO events(instrument_id,ts,class,detail,is_public) VALUES(?,NOW(),?,?,1)')
20 ->execute([$i['id'],$class, $i['name'].': '.$i['status'].' → '.$new]);
21 log_activity('cron','health_transition',$i['name'].' '.$i['status'].'→'.$new);
22 if(in_array($new,['late','silent'])){
23 $throttled = $i['last_alert_at'] && (time()-strtotime($i['last_alert_at']) < ALERT_THROTTLE_HOURS*3600);
24 if(!$throttled){
25 @mail(ALERT_EMAIL,'[Research Labs] '.$i['name'].' is '.$new,
26 $i['name'].' ('.$i['product'].") transitioned to ".$new.".\nLast reading: ".($last?:'never')."\nHealth: ".BASE_URL."/index.php?p=health",
27 'From: '.ALERT_FROM);
28 db()->prepare('UPDATE instruments SET last_alert_at=NOW() WHERE id=?')->execute([$i['id']]);
29 log_activity('cron','alert_email',$i['name'].' '.$new);
30 }
31 }
32 }
33}
34echo "health check complete\n";
35

Lines can be cited as cron/health_check.php L120-L140, platform code 2026.09.17-a2894de; add #L120-L140 to this page's address to highlight them. Source shown for scrutiny of the research platform. All rights reserved. Not offered as installable software.