refactor: timer update

This commit is contained in:
Carlos Valente
2024-07-16 21:29:31 +02:00
committed by Carlos Valente
parent cb773ded9f
commit edc7f20d7a
7 changed files with 195 additions and 397 deletions
+20 -10
View File
@@ -4,6 +4,8 @@ import * as runtimeState from '../stores/runtimeState.js';
import type { UpdateResult } from '../stores/runtimeState.js';
import { timerConfig } from '../config/config.js';
type UpdateCallbackFn = (updateResult: UpdateResult) => void;
/**
* Service manages Ontime's main timer
*/
@@ -13,9 +15,9 @@ export class TimerService {
static _refreshInterval: number;
/** when timer will be finished */
private endCallback: NodeJS.Timeout;
private endCallback: NodeJS.Timeout | undefined = undefined;
private onUpdateCallback: (updateResult: UpdateResult) => void;
private onUpdateCallback: UpdateCallbackFn | undefined = undefined;
/**
* @constructor
@@ -23,19 +25,21 @@ export class TimerService {
* @param {number} [timerConfig.updateInterval] how often we update the socket
* @param {function} [timerConfig.onUpdateCallback] how often we update the socket
*/
constructor(timerConfig: {
refresh: number;
updateInterval: number;
onUpdateCallback: (updateResult: UpdateResult) => void;
}) {
constructor(timerConfig: { refresh: number; updateInterval: number }) {
TimerService._refreshInterval = timerConfig.refresh;
this.onUpdateCallback = timerConfig.onUpdateCallback;
this._interval = setInterval(() => {
this.update();
}, TimerService._refreshInterval);
}
/**
* Allows setting a callback for when the timer updates
* @param callback
*/
setOnUpdateCallback(callback: (updateResult: UpdateResult) => void) {
this.onUpdateCallback = callback;
}
start() {
if (!runtimeState.start()) {
return false;
@@ -79,6 +83,12 @@ export class TimerService {
// renew end callback
clearTimeout(this.endCallback);
const state = runtimeState.getState();
// eslint-disable-next-line no-unused-labels -- dev code path
DEV: {
if (state.timer.expectedFinish === null) {
throw new Error('TimerService.addTime: expectedFinish is negative');
}
}
this.endCallback = setTimeout(() => this.update(), state.timer.expectedFinish);
return true;
}
@@ -89,7 +99,7 @@ export class TimerService {
update() {
const updateResult = runtimeState.update();
// pass the result to the parent
this.onUpdateCallback(updateResult);
this.onUpdateCallback?.(updateResult);
}
/**
@@ -10,7 +10,6 @@ import {
getTotalDuration,
normaliseEndTime,
skippedOutOfEvent,
updateRoll,
} from '../timerUtils.js';
import { RuntimeState } from '../../stores/runtimeState.js';
@@ -1237,196 +1236,6 @@ test('normaliseEndTime()', () => {
expect(normaliseEndTime(t3.start, t3.end)).toBe(t3_expected);
});
describe('updateRoll()', () => {
it('it updates running events correctly', () => {
const timers = {
eventNow: {
id: '1',
},
clock: 11,
timer: {
current: 10,
expectedFinish: 100,
secondaryTimer: null,
startedAt: 1,
},
_timer: {
secondaryTarget: null,
},
} as RuntimeState;
const expected = {
updatedTimer: 100 - 11,
updatedSecondaryTimer: null, // usually clock - expectedFinish
doRollLoad: false,
isFinished: false,
};
expect(updateRoll(timers)).toStrictEqual(expected);
// test that it can jump time
timers.timer.expectedFinish = 1000;
timers.clock = 600;
expected.updatedTimer = 1000 - 600;
expect(updateRoll(timers)).toStrictEqual(expected);
});
it('it updates secondary timer', () => {
const timers = {
eventNow: null,
clock: 11,
timer: {
current: null,
expectedFinish: null,
secondaryTimer: 1,
},
_timer: {
secondaryTarget: 15,
},
} as RuntimeState;
const expected = {
updatedTimer: null,
updatedSecondaryTimer: 15 - 11, // countdown to secondary
doRollLoad: false,
isFinished: false,
};
expect(updateRoll(timers)).toStrictEqual(expected);
});
it('flags an event end', () => {
const timers = {
eventNow: {
id: '1',
},
clock: 12,
timer: {
startedAt: 0,
current: 10,
expectedFinish: 11,
secondaryTimer: null,
},
_timer: {
secondaryTarget: null,
},
} as RuntimeState;
const expected = {
updatedTimer: -1,
updatedSecondaryTimer: null,
doRollLoad: true,
isFinished: true,
};
expect(updateRoll(timers)).toStrictEqual(expected);
});
it('secondary events do not trigger event ends', () => {
const timers = {
eventNow: null,
clock: 16,
timer: {
startedAt: null,
current: null,
expectedFinish: null,
secondaryTimer: 1,
},
_timer: {
secondaryTarget: 15,
},
} as RuntimeState;
const expected = {
updatedTimer: null,
updatedSecondaryTimer: -1,
doRollLoad: true,
isFinished: false,
};
expect(updateRoll(timers)).toStrictEqual(expected);
});
it('when a secondary timer is finished, it prompts for new event load', () => {
const timers = {
eventNow: null,
clock: 15,
timer: {
current: null,
expectedFinish: null,
secondaryTimer: 0,
},
_timer: {
secondaryTarget: 15,
},
} as RuntimeState;
const expected = {
updatedTimer: null,
updatedSecondaryTimer: 0,
doRollLoad: true,
isFinished: false,
};
expect(updateRoll(timers)).toStrictEqual(expected);
});
it('counts over midnight', () => {
const timers = {
eventNow: {
id: '1',
},
clock: dayInMs - 10,
timer: {
current: 25,
expectedFinish: 10,
startedAt: 1000,
secondaryTimer: null,
},
_timer: {
secondaryTarget: null,
},
} as RuntimeState;
const expected = {
updatedTimer: 20,
updatedSecondaryTimer: null,
doRollLoad: false,
isFinished: false,
};
expect(updateRoll(timers)).toStrictEqual(expected);
});
it('rolls over midnight', () => {
const timers = {
eventNow: {
id: '1',
},
clock: 10,
timer: {
current: dayInMs,
expectedFinish: 10,
startedAt: 1000,
secondaryTimer: null,
},
_timer: {
secondaryTarget: null,
},
} as RuntimeState;
const expected = {
updatedTimer: dayInMs,
updatedSecondaryTimer: null,
doRollLoad: false,
isFinished: false,
};
expect(updateRoll(timers)).toStrictEqual(expected);
});
});
describe('getRuntimeOffset()', () => {
it('is the difference between scheduled and when we actually started', () => {
const state = {
@@ -1554,7 +1363,7 @@ describe('getRuntimeOffset()', () => {
secondaryTimer: null,
startedAt: null,
},
_timer: { pausedAt: null, secondaryTarget: null },
_timer: { pausedAt: null },
} as RuntimeState;
const offset = getRuntimeOffset(state);
@@ -1595,7 +1404,7 @@ describe('getRuntimeOffset()', () => {
secondaryTimer: null,
startedAt: null,
},
_timer: { pausedAt: null, secondaryTarget: null },
_timer: { pausedAt: null },
} as RuntimeState;
const offset = getRuntimeOffset(state);
@@ -1630,7 +1439,7 @@ describe('getRuntimeOffset()', () => {
runtime: {
selectedEventIndex: 0,
numEvents: 1,
offset: null,
offset: 0,
plannedStart: 77400000, // 21:30:00
plannedEnd: 81000000, // 22:30:00
actualStart: 78000000, // 21:40:00
@@ -1647,7 +1456,7 @@ describe('getRuntimeOffset()', () => {
secondaryTimer: null,
startedAt: 78000000,
},
_timer: { pausedAt: null, secondaryTarget: null },
_timer: { pausedAt: null },
} as RuntimeState;
const offset = getRuntimeOffset(state);
@@ -1682,7 +1491,7 @@ describe('getRuntimeOffset()', () => {
runtime: {
selectedEventIndex: 0,
numEvents: 1,
offset: null,
offset: 0,
plannedStart: 77400000, // 21:30:00
plannedEnd: 81000000, // 22:30:00
actualStart: 78000000, // 21:40:00
@@ -1699,7 +1508,7 @@ describe('getRuntimeOffset()', () => {
secondaryTimer: null,
startedAt: 78000000,
},
_timer: { pausedAt: null, secondaryTarget: null },
_timer: { pausedAt: null },
} as RuntimeState;
const offset = getRuntimeOffset(state);
@@ -1722,7 +1531,7 @@ describe('getRuntimeOffset()', () => {
runtime: {
selectedEventIndex: 0,
numEvents: 1,
offset: null,
offset: 0,
plannedStart: 77400000, // 21:30:00
plannedEnd: 81000000, // 22:30:00
actualStart: 82000000, // 22:46:40 <--- started now
@@ -1739,7 +1548,7 @@ describe('getRuntimeOffset()', () => {
secondaryTimer: null,
startedAt: 82000000, // <--- started now
},
_timer: { pausedAt: null, secondaryTarget: null },
_timer: { pausedAt: null },
} as RuntimeState;
const updateCurrent = getCurrent(state);
@@ -1887,7 +1696,7 @@ describe('getTimerPhase()', () => {
runtime: {
selectedEventIndex: null,
numEvents: 1,
offset: null,
offset: 0,
plannedStart: 55860000,
plannedEnd: 55880000,
actualStart: null,
@@ -1909,7 +1718,6 @@ describe('getTimerPhase()', () => {
forceFinish: null,
totalDelay: 0,
pausedAt: null,
secondaryTarget: 55860000,
},
} as RuntimeState;
@@ -1927,7 +1735,7 @@ describe('getTimerPhase()', () => {
runtime: {
selectedEventIndex: null,
numEvents: 1,
offset: null,
offset: 0,
plannedStart: 55860000,
plannedEnd: 55880000,
actualStart: null,
@@ -1949,7 +1757,6 @@ describe('getTimerPhase()', () => {
forceFinish: null,
totalDelay: 0,
pausedAt: null,
secondaryTarget: 55860000,
},
} as RuntimeState;
@@ -29,7 +29,9 @@ import {
getEventWithId,
getPlayableEvents,
} from '../rundown-service/rundownUtils.js';
import { skippedOutOfEvent } from '../timerUtils.js';
import { integrationService } from '../integration-service/IntegrationService.js';
import { getForceUpdate, getShouldClockUpdate, getShouldTimerUpdate } from './rundownService.utils.js';
/**
@@ -37,18 +39,21 @@ import { getForceUpdate, getShouldClockUpdate, getShouldTimerUpdate } from './ru
* Coordinating with necessary services
*/
class RuntimeService {
private eventTimer: TimerService | null = null;
private eventTimer: TimerService;
private lastIntegrationClockUpdate = -1;
private lastIntegrationTimerValue = -1;
/** last time we updated the socket */
static previousTimerUpdate: number;
static previousTimerValue: MaybeNumber;
static previousTimerValue: MaybeNumber; // previous timer value, could be null
static previousClockUpdate: number;
/** last known state */
static previousState: RuntimeState;
constructor() {
constructor(timerService: TimerService) {
this.eventTimer = timerService;
RuntimeService.previousTimerUpdate = -1;
RuntimeService.previousTimerValue = -1;
RuntimeService.previousClockUpdate = -1;
@@ -59,7 +64,45 @@ class RuntimeService {
@broadcastResult
checkTimerUpdate({ shouldCallRoll, hasTimerFinished }: runtimeState.UpdateResult) {
const newState = runtimeState.getState();
if (hasTimerFinished) {
// 1. find if we need to dispatch integrations related to the phase
const timerPhaseChanged = RuntimeService.previousState.timer?.phase !== newState.timer.phase;
if (timerPhaseChanged) {
if (newState.timer.phase === TimerPhase.Warning) {
process.nextTick(() => {
integrationService.dispatch(TimerLifeCycle.onWarning);
});
} else if (newState.timer.phase === TimerPhase.Danger) {
process.nextTick(() => {
integrationService.dispatch(TimerLifeCycle.onDanger);
});
}
}
// 2. handle edge cases related to roll
if (newState.timer.playback === Playback.Roll) {
// check if we need to call roll again
const needsEvent =
newState.eventNow === null
? true
: skippedOutOfEvent(newState, this.lastIntegrationClockUpdate, timerConfig.skipLimit);
const hasFinishedRoll = hasTimerFinished && shouldCallRoll;
if (shouldCallRoll || needsEvent) {
if (hasFinishedRoll) {
process.nextTick(() => {
integrationService.dispatch(TimerLifeCycle.onFinish);
});
}
// we dont call this.roll because we need to bypass the checks
const rundown = getPlayableEvents();
// TODO: by not calling roll, we dont get the events
this.eventTimer.roll(rundown);
}
}
// 3. find if we need to process actions related to the timer finishing
if (newState.timer.playback !== Playback.Roll && hasTimerFinished) {
process.nextTick(() => {
integrationService.dispatch(TimerLifeCycle.onFinish);
});
@@ -77,10 +120,8 @@ class RuntimeService {
}
}
const hasRunningTimer = Boolean(newState.eventNow) && newState.timer.playback === Playback.Play;
const shouldUpdateTimer =
hasRunningTimer && getShouldTimerUpdate(this.lastIntegrationTimerValue, newState.timer.current);
// 4. find if we need to update the timer
const shouldUpdateTimer = getShouldTimerUpdate(this.lastIntegrationTimerValue, newState.timer.current);
if (shouldUpdateTimer) {
process.nextTick(() => {
integrationService.dispatch(TimerLifeCycle.onUpdate);
@@ -89,6 +130,7 @@ class RuntimeService {
this.lastIntegrationTimerValue = newState.timer.current ?? -1;
}
// 5. find if we need to update the clock
const shouldUpdateClock = getShouldClockUpdate(this.lastIntegrationClockUpdate, newState.clock);
if (shouldUpdateClock) {
process.nextTick(() => {
@@ -97,42 +139,12 @@ class RuntimeService {
this.lastIntegrationClockUpdate = newState.clock;
}
if (shouldCallRoll) {
// we dont call this.roll because we need to bypass the checks
const rundown = getPlayableEvents();
this.eventTimer.roll(rundown);
}
const timerPhaseChanged = RuntimeService.previousState.timer?.phase !== newState.timer.phase;
if (timerPhaseChanged) {
switch (newState.timer.phase) {
case TimerPhase.Warning:
process.nextTick(() => {
integrationService.dispatch(TimerLifeCycle.onWarning);
});
break;
case TimerPhase.Danger:
process.nextTick(() => {
integrationService.dispatch(TimerLifeCycle.onDanger);
});
break;
default:
break;
}
}
}
/** delay initialisation until we have a restore point */
init(resumable: RestorePoint | null) {
logger.info(LogOrigin.Server, 'Runtime service started');
// calculate at 30fps, refresh at 1fps
this.eventTimer = new TimerService({
refresh: timerConfig.updateRate,
updateInterval: timerConfig.notificationRate,
onUpdateCallback: (updateResult) => this.checkTimerUpdate(updateResult),
});
this.eventTimer.setOnUpdateCallback((updateResult) => this.checkTimerUpdate(updateResult));
if (resumable) {
this.resume(resumable);
@@ -553,8 +565,16 @@ class RuntimeService {
}
}
export const runtimeService = new RuntimeService();
// calculate at 30fps, refresh at 1fps
const eventTimer = new TimerService({
refresh: timerConfig.updateRate,
updateInterval: timerConfig.notificationRate,
});
export const runtimeService = new RuntimeService(eventTimer);
/**
* Decorator manages side effects from updating the runtime
*/
function broadcastResult(_target: any, _propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
+22 -51
View File
@@ -1,7 +1,6 @@
import { MaybeNumber, MaybeString, OntimeEvent, Playback, TimerPhase, TimerType } from 'ontime-types';
import { dayInMs } from 'ontime-utils';
import { RuntimeState } from '../stores/runtimeState.js';
import { timerConfig } from '../config/config.js';
/**
* handle events that span over midnight
@@ -56,6 +55,12 @@ export function getExpectedFinish(state: RuntimeState): MaybeNumber {
*/
export function getCurrent(state: RuntimeState): number {
// eslint-disable-next-line no-unused-labels -- dev code path
DEV: {
if (state.eventNow === null || state.timer.duration === null) {
throw new Error('timerUtils.getCurrent: invalid state received');
}
}
const { startedAt, duration, addedTime } = state.timer;
const { timerType, timeStart, timeEnd } = state.eventNow;
const { pausedAt } = state._timer;
@@ -88,6 +93,12 @@ export function getCurrent(state: RuntimeState): number {
* @returns {boolean}
*/
export function skippedOutOfEvent(state: RuntimeState, previousTime: number, skipLimit: number): boolean {
// eslint-disable-next-line no-unused-labels -- dev code path
DEV: {
if (state.timer.expectedFinish === null || state.timer.startedAt === null) {
throw new Error('timerUtils.skippedOutOfEvent: invalid state received');
}
}
const { startedAt, expectedFinish } = state.timer;
const { clock } = state;
@@ -246,54 +257,6 @@ export const getRollTimers = (rundown: OntimeEvent[], timeNow: number, currentIn
};
};
/**
* @description Implements update functions for roll mode
* @param {RuntimeState}
* @returns object with selection variables
*/
export const updateRoll = (state: RuntimeState) => {
const { current, expectedFinish, startedAt, secondaryTimer } = state.timer;
const { secondaryTarget } = state._timer;
const { clock } = state;
const selectedEventId = state.eventNow?.id ?? null;
// timers
let updatedTimer = current;
let updatedSecondaryTimer = secondaryTimer;
// whether rollLoad should be called: force reload of events
let doRollLoad = false;
// whether finished event should trigger
let isPrimaryFinished = false;
if (selectedEventId && current !== null) {
// if we have something selected and a timer, we are running
const finishAt = expectedFinish >= startedAt ? expectedFinish : expectedFinish + dayInMs;
updatedTimer = finishAt - clock;
if (updatedTimer > dayInMs) {
updatedTimer -= dayInMs;
}
if (updatedTimer <= timerConfig.triggerAhead) {
isPrimaryFinished = true;
// we need a new event
doRollLoad = true;
}
} else if (secondaryTimer >= 0) {
// if secondaryTimer is running we are in waiting to roll
updatedSecondaryTimer = secondaryTarget - clock;
if (updatedSecondaryTimer <= 0) {
// we need a new event
doRollLoad = true;
}
}
return { updatedTimer, updatedSecondaryTimer, doRollLoad, isFinished: isPrimaryFinished };
};
/**
* Calculates difference between the runtime and the schedule of an event
* Positive offset is time ahead
@@ -305,6 +268,14 @@ export function getRuntimeOffset(state: RuntimeState): number {
return 0;
}
// eslint-disable-next-line no-unused-labels -- dev code path
DEV: {
// we know current exists as long as eventNow exists
if (state.timer.current === null) {
throw new Error('timerUtils.calculate: current must be set');
}
}
const { clock } = state;
const { timeStart, timerType } = state.eventNow;
const { addedTime, current, startedAt } = state.timer;
@@ -356,7 +327,7 @@ export function getTotalDuration(firstStart: number, lastEnd: number, daySpan: n
*/
export function getExpectedEnd(state: RuntimeState): MaybeNumber {
// there is no expected end if we havent started
if (state.runtime.actualStart === null) {
if (state.runtime.actualStart === null || state.runtime.plannedEnd === null) {
return null;
}
return state.runtime.plannedEnd - state.runtime.offset + state._timer.totalDelay;
@@ -367,7 +338,7 @@ export function getExpectedEnd(state: RuntimeState): MaybeNumber {
* @param state
* @returns
*/
function isPlaybackActive(state: RuntimeState): boolean {
export function isPlaybackActive(state: RuntimeState): boolean {
return (
state.timer.playback === Playback.Play ||
state.timer.playback === Playback.Pause ||