Improve determination of when a state change may need to be reported

Change-type: patch
Signed-off-by: Ken Bannister <kb2ma@runbox.com>
This commit is contained in:
Ken Bannister 2022-11-18 09:23:20 -05:00
parent b1d4aa5159
commit 599b5cf811

View File

@ -167,11 +167,15 @@ export async function startReporting() {
} }
let reportPending = false; let reportPending = false;
// Reports current state if not already sending and does not exceed report // Reports current state if not already sending and prevents a state change
// frequency. Returns true if sent; otherwise false. // from exceeding report frequency. Returns true if sent; otherwise false.
const doReport = async (): Promise<boolean> => { const doReport = async (): Promise<boolean> => {
if (!reportPending) { if (!reportPending) {
if (performance.now() - lastReportTime > maxReportFrequency) { if (performance.now() - lastReportTime > maxReportFrequency) {
// Can't wait until report complete to clear deferred marker.
// Change events while in progress will set deferred marker synchronously.
// Ensure we don't miss reporting a change event.
stateChangeDeferred = false;
reportPending = true; reportPending = true;
await reportCurrentState(reportConfigs, uuid); await reportCurrentState(reportConfigs, uuid);
reportPending = false; reportPending = false;
@ -185,9 +189,12 @@ export async function startReporting() {
}; };
const onStateChange = async () => { const onStateChange = async () => {
// Defers to timed report schedule if we can't report immediately. // State change events are async, but may arrive in rapid succession.
// Ensures that we always report on a change event. // Defers to a timed report schedule if we can't report immediately, to
stateChangeDeferred = !(await doReport()); // ensure we don't miss reporting an event.
if (!(await doReport())) {
stateChangeDeferred = true;
}
}; };
// If the state changes, report it // If the state changes, report it
@ -197,7 +204,9 @@ export async function startReporting() {
try { try {
// Follow-up when report not sent immediately on change event... // Follow-up when report not sent immediately on change event...
if (stateChangeDeferred) { if (stateChangeDeferred) {
stateChangeDeferred = !(await doReport()); if (!(await doReport())) {
stateChangeDeferred = true;
}
} else { } else {
// ... or on regular metrics schedule. // ... or on regular metrics schedule.
if (performance.now() - lastReportTime > maxMetricsFrequency) { if (performance.now() - lastReportTime > maxMetricsFrequency) {