fix: harden loadHistory against race conditions and canvas reuse

This commit is contained in:
2026-08-09 18:03:41 +07:00
parent b3ea340bbd
commit 32e455783a
+14 -7
View File
@@ -206,7 +206,7 @@
<script> <script>
(function () { (function () {
'use strict'; 'use strict';
const state = { map: null, layers: [], markers: new Map(), hasFit: false, historyChart: null, selectedStation: null }; const state = { map: null, layers: [], markers: new Map(), hasFit: false, historyChart: null, selectedStation: null, historyRequestId: 0 };
const $ = (id) => document.getElementById(id); const $ = (id) => document.getElementById(id);
function flowColor(flow) { function flowColor(flow) {
@@ -318,25 +318,26 @@
async function loadHistory(stationCode) { async function loadHistory(stationCode) {
state.selectedStation = stationCode; state.selectedStation = stationCode;
state.historyRequestId++;
const reqId = state.historyRequestId;
$('history-title').textContent = `${stationCode} · PostgreSQL history`; $('history-title').textContent = `${stationCode} · PostgreSQL history`;
$('history-status').textContent = 'Loading historical measurements…'; $('history-status').textContent = 'Loading historical measurements…';
if (state.historyChart) { state.historyChart.destroy(); state.historyChart = null; }
try { try {
const response = await fetch(`/measurements/history/${encodeURIComponent(stationCode)}?hours=${$('history-range').value}`); const response = await fetch(`/measurements/history/${encodeURIComponent(stationCode)}?hours=${$('history-range').value}`);
if (!response.ok) throw new Error((await response.json()).detail || `HTTP ${response.status}`); if (!response.ok) throw new Error((await response.json()).detail || `HTTP ${response.status}`);
const rows = await response.json(); const rows = await response.json();
if (reqId !== state.historyRequestId) return;
// Downsample to daily averages to prevent browser freezing with 50k+ points // Downsample to daily averages to prevent browser freezing with 50k+ points
const downsample = (data) => { const downsample = (data) => {
const buckets = {}; const buckets = {};
data.forEach((row, i) => { data.forEach((row) => {
const date = new Date(row.timestamp); const date = new Date(row.timestamp);
const key = `${date.getUTCFullYear()}-${date.getUTCMonth()}-${date.getUTCDate()}`; const key = `${date.getUTCFullYear()}-${date.getUTCMonth()}-${date.getUTCDate()}`;
if (!buckets[key]) buckets[key] = { ts: row.timestamp, discharge: [], level: [], count: 0 }; if (!buckets[key]) buckets[key] = { ts: row.timestamp, discharge: [], level: [] };
const b = buckets[key]; const b = buckets[key];
if (row.discharge != null) b.discharge.push(row.discharge); if (row.discharge != null) b.discharge.push(row.discharge);
if (row.water_level != null) b.level.push(row.water_level); if (row.water_level != null) b.level.push(row.water_level);
b.count++;
}); });
return Object.values(buckets).map((b) => ({ return Object.values(buckets).map((b) => ({
timestamp: b.ts, timestamp: b.ts,
@@ -344,8 +345,14 @@
water_level: b.level.length ? b.level.reduce((a, c) => a + c, 0) / b.level.length : null, water_level: b.level.length ? b.level.reduce((a, c) => a + c, 0) / b.level.length : null,
})); }));
}; };
const sampled = rows.length > 2000 ? downsample(rows) : rows; const sampled = rows.length > 2000 ? downsample(rows) : rows;
// Safely clear existing chart instance
if (state.historyChart) { state.historyChart.destroy(); state.historyChart = null; }
// Clear any orphan Chart.js instance on the canvas
const existingChart = Chart.getChart($('history-chart'));
if (existingChart) existingChart.destroy();
state.historyChart = new Chart($('history-chart'), { state.historyChart = new Chart($('history-chart'), {
type: 'line', type: 'line',
data: { data: {
@@ -365,7 +372,7 @@
}, },
plugins: [{ plugins: [{
id: 'flood-bands', id: 'flood-bands',
beforeDraw(chart, _args, options) { beforeDraw(chart) {
const levelScale = chart.scales?.level; const levelScale = chart.scales?.level;
if (!levelScale || levelScale.min == null) return; if (!levelScale || levelScale.min == null) return;
const zones = [ const zones = [