Skip to content

Add validation to Heartbeat record to prevent EndTime before StartTime #38

@hughesjs

Description

@hughesjs

Issue

The Heartbeat record currently allows EndTime to be earlier than StartTime, which represents an invalid state.

Location

src/Lazarus/Public/Watchdog/Heartbeat.cs:6-22

Problem

A heartbeat with EndTime before StartTime is logically invalid and could lead to negative time spans or other unexpected behaviour in downstream calculations.

Proposed Solution

Convert to a primary constructor with validation:

public record Heartbeat(DateTimeOffset StartTime, DateTimeOffset EndTime, Exception? Exception = null)
{
    public Heartbeat(DateTimeOffset StartTime, DateTimeOffset EndTime, Exception? Exception = null)
    {
        if (EndTime < StartTime)
        {
            throw new ArgumentException($"EndTime ({EndTime}) cannot be earlier than StartTime ({StartTime})", nameof(EndTime));
        }
        
        this.StartTime = StartTime;
        this.EndTime = EndTime;
        this.Exception = Exception;
    }
}

This ensures:

  • Invalid heartbeat instances cannot be created
  • Clear error messages at construction time
  • Preservation of the nullable Exception parameter

Identified during code review of PR #35

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions