feat(companion): add heartbeat loop success callback
This commit is contained in:
@@ -81,6 +81,21 @@ describe('CompanionHeartbeatLoop', () => {
|
||||
loop.stop();
|
||||
});
|
||||
|
||||
it('calls onSuccess with heartbeat result payload', async () => {
|
||||
const result = buildStatusResult();
|
||||
const publishHeartbeat = vi.fn(async () => result);
|
||||
const onSuccess = vi.fn();
|
||||
const loop = new CompanionHeartbeatLoop(
|
||||
{ publishHeartbeat },
|
||||
{ intervalMs: 200, onSuccess },
|
||||
);
|
||||
|
||||
loop.start();
|
||||
await Promise.resolve();
|
||||
expect(onSuccess).toHaveBeenCalledWith(result);
|
||||
loop.stop();
|
||||
});
|
||||
|
||||
it('passes buildHeartbeat payload into publishHeartbeat', async () => {
|
||||
const publishHeartbeat = vi.fn(async () => buildStatusResult());
|
||||
const buildHeartbeat = vi.fn(() => ({ statusText: 'loop', powerSource: 'ac' as const }));
|
||||
|
||||
@@ -9,6 +9,7 @@ export interface CompanionHeartbeatLoopOptions {
|
||||
intervalMs?: number;
|
||||
jitterRatio?: number;
|
||||
buildHeartbeat?: () => HeartbeatStatusInput | Promise<HeartbeatStatusInput>;
|
||||
onSuccess?: (result: NodeStatusSetResult) => void;
|
||||
onError?: (error: Error) => void;
|
||||
maxConsecutiveFailures?: number;
|
||||
onFailureLimitReached?: (error: Error, consecutiveFailures: number) => void;
|
||||
@@ -24,6 +25,7 @@ export class CompanionHeartbeatLoop {
|
||||
private readonly intervalMs: number;
|
||||
private readonly jitterRatio: number;
|
||||
private readonly buildHeartbeat?: () => HeartbeatStatusInput | Promise<HeartbeatStatusInput>;
|
||||
private readonly onSuccess?: (result: NodeStatusSetResult) => void;
|
||||
private readonly onError?: (error: Error) => void;
|
||||
private readonly maxConsecutiveFailures: number;
|
||||
private readonly onFailureLimitReached?: (error: Error, consecutiveFailures: number) => void;
|
||||
@@ -56,6 +58,7 @@ export class CompanionHeartbeatLoop {
|
||||
this.intervalMs = intervalMs;
|
||||
this.jitterRatio = jitterRatio;
|
||||
this.buildHeartbeat = options.buildHeartbeat;
|
||||
this.onSuccess = options.onSuccess;
|
||||
this.onError = options.onError;
|
||||
this.maxConsecutiveFailures = maxConsecutiveFailures;
|
||||
this.onFailureLimitReached = options.onFailureLimitReached;
|
||||
@@ -129,9 +132,10 @@ export class CompanionHeartbeatLoop {
|
||||
this.inFlight = true;
|
||||
try {
|
||||
const payload = this.buildHeartbeat ? await this.buildHeartbeat() : undefined;
|
||||
await this.publisher.publishHeartbeat(payload);
|
||||
const result = await this.publisher.publishHeartbeat(payload);
|
||||
this.consecutiveFailures = 0;
|
||||
this.lastError = null;
|
||||
this.onSuccess?.(result);
|
||||
} catch (error) {
|
||||
const err = error instanceof Error ? error : new Error(String(error));
|
||||
this.consecutiveFailures += 1;
|
||||
|
||||
Reference in New Issue
Block a user