src/Trace-Health.psm1

#requires -Version 5

<#
.SYNOPSIS
    Executes and monitors a script reporting the start, success and any failures.
.EXAMPLE Basic Example
    $scriptOutput = Trace-Health {
        Write-Host "This is my awesome script!"

        return $true
    } -CheckUUID "1a468c9a-ac84-4add-978b-593ab4b43c6b"
#>

function Trace-Health {
    [CmdletBinding()]
    Param(
        # The scriptblock to execute and monitor the health of
        [Parameter(Mandatory)]
        [scriptblock]
        $Scriptblock,

        # The UUID of the health check
        [Parameter(Mandatory)]
        [guid] $CheckUUID
    )

    Send-HealthchecksIOPing -Type "start" -CheckUUID $CheckUUID

    try {
        $result = $Scriptblock.InvokeReturnAsIs()

        Send-HealthchecksIOPing -CheckUUID $CheckUUID

        return $result
    } catch {
        Send-HealthchecksIOPing -Type "fail" -CheckUUID $CheckUUID
        throw $_
    }
}

function Send-HealthchecksIOPing {
    [CmdletBinding()]
    Param(
        # The UUID of the health check
        [Parameter(Mandatory)]
        [guid] $CheckUUID,

        # The type of ping to send
        [Parameter()]
        [ValidateSet("", "fail", "start")]
        [string] $Type = ""
    )

    if ($Type -eq "") {
        $logType = "success"
    } else {
        $logType = $Type
    }

    Write-Verbose "Reporting $logType of '$CheckUUID' to healthchecks.io..."

    try {
        $uri = "https://hc-ping.com/$CheckUUID"
        if ($Type -ne "") {
            $uri += "/$Type"
        }

        Invoke-RestMethod `
            -Method "POST" `
            -Uri $uri `
            -ErrorAction Stop `
            | Out-Null
    } catch {
        Write-Warning "Failed to send $logType ping to healthchecks.io for '$CheckUUID': $($_.Message)"
        $_ | Write-Verbose
    }
}