Compare commits
4 Commits
0956271e29
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7522e9e0f3 | ||
|
|
0ab0168a8d | ||
|
|
a73105586b | ||
|
|
c6ff80655b |
42
go-health/liveness.go
Normal file
42
go-health/liveness.go
Normal file
@@ -0,0 +1,42 @@
|
||||
package health
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Status of the service liveness.
|
||||
type LivenessStatus string
|
||||
|
||||
const (
|
||||
// Service is alive and functioning properly.
|
||||
LivenessStatusAlive LivenessStatus = "ok"
|
||||
)
|
||||
|
||||
// Result of a liveness check.
|
||||
type LivenessResult struct {
|
||||
// Status of the service (always LivenessStatusAlive)
|
||||
Status LivenessStatus
|
||||
// Timestamp of the liveness check in milliseconds since Unix epoch
|
||||
Timestamp int64
|
||||
}
|
||||
|
||||
// Checks if the service is alive.
|
||||
func Liveness() LivenessResult {
|
||||
return LivenessResult{
|
||||
Status: LivenessStatusAlive,
|
||||
Timestamp: time.Now().UnixMilli(),
|
||||
}
|
||||
}
|
||||
|
||||
// Handler for liveness HTTP requests.
|
||||
// Returns a response with status 200 and a JSON body matching LivenessResult.
|
||||
func LivenessHandler() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
result := Liveness()
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(result)
|
||||
}
|
||||
}
|
||||
221
go-health/readiness.go
Normal file
221
go-health/readiness.go
Normal file
@@ -0,0 +1,221 @@
|
||||
package health
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"slices"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Status of the service readiness.
|
||||
type ReadinessStatus string
|
||||
|
||||
// String returns the string representation of the readiness status.
|
||||
func (s ReadinessStatus) String() string {
|
||||
return string(s)
|
||||
}
|
||||
|
||||
// HTTPStatus returns the corresponding HTTP status code for the readiness status.
|
||||
func (s ReadinessStatus) HTTPStatus() int {
|
||||
switch s {
|
||||
case ReadinessStatusReady:
|
||||
return http.StatusOK
|
||||
case ReadinessStatusDegraded:
|
||||
return http.StatusOK // 206 could also be suitable, but let's avoid false alarms
|
||||
case ReadinessStatusFatal:
|
||||
return http.StatusServiceUnavailable
|
||||
case ReadinessStatusNotReady:
|
||||
return http.StatusOK // treat as ok to avoid false alarms
|
||||
default:
|
||||
return http.StatusOK
|
||||
}
|
||||
}
|
||||
|
||||
const (
|
||||
// Service is ready to handle requests.
|
||||
ReadinessStatusReady ReadinessStatus = "ready"
|
||||
// Service is not ready to handle requests.
|
||||
ReadinessStatusNotReady ReadinessStatus = "not_ready"
|
||||
// Service experienced a fatal error and cannot handle requests.
|
||||
ReadinessStatusFatal ReadinessStatus = "fatal"
|
||||
// Service is degraded but can still handle requests.
|
||||
ReadinessStatusDegraded ReadinessStatus = "degraded"
|
||||
)
|
||||
|
||||
// Returns the worst readiness status from a list of statuses.
|
||||
func worstStatus(statuses []ReadinessStatus) ReadinessStatus {
|
||||
if slices.Contains(statuses, ReadinessStatusFatal) {
|
||||
return ReadinessStatusFatal
|
||||
}
|
||||
if slices.Contains(statuses, ReadinessStatusNotReady) {
|
||||
return ReadinessStatusNotReady
|
||||
}
|
||||
if slices.Contains(statuses, ReadinessStatusDegraded) {
|
||||
return ReadinessStatusDegraded
|
||||
}
|
||||
return ReadinessStatusReady
|
||||
}
|
||||
|
||||
// Readiness check function return type.
|
||||
type ReadinessReturn struct {
|
||||
// Status of the readiness check.
|
||||
Status ReadinessStatus
|
||||
// Optional message providing additional information about the readiness status.
|
||||
Message *string
|
||||
}
|
||||
|
||||
// Function that performs a readiness check.
|
||||
type ReadinessCheckFn func() ReadinessReturn
|
||||
|
||||
// Individual readiness check.
|
||||
type ReadinessCheck struct {
|
||||
// Name of the readiness check.
|
||||
Name string
|
||||
// Function that performs the readiness check.
|
||||
Fn ReadinessCheckFn
|
||||
// Timeout for the readiness check (default: 5 seconds)
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
// System-generated result from an individual readiness check.
|
||||
type ReadinessCheckResult struct {
|
||||
// Name of the readiness check.
|
||||
Name string
|
||||
// Status of the readiness check.
|
||||
Status ReadinessStatus
|
||||
// Optional message providing additional information about the readiness status.
|
||||
Message *string
|
||||
// Duration of the readiness check in milliseconds.
|
||||
Duration int64
|
||||
}
|
||||
|
||||
// System readiness status.
|
||||
type Readiness struct {
|
||||
// Status of the service readiness. Aggregated as the worst status from
|
||||
// all individual readiness checks. If no checks have been performed
|
||||
// yet, the status is ReadinessStatusNotReady.
|
||||
Status ReadinessStatus
|
||||
// Start time of the readiness check in milliseconds since Unix epoch.
|
||||
Start int64
|
||||
// Duration of the readiness check in milliseconds.
|
||||
Duration int64
|
||||
// Individual readiness check results.
|
||||
Details map[string]ReadinessCheckResult
|
||||
}
|
||||
|
||||
// Performs a full system readiness check given a list of individual checks.
|
||||
func CheckReadiness(checks []ReadinessCheck) Readiness {
|
||||
start := time.Now()
|
||||
details := make(map[string]ReadinessCheckResult)
|
||||
var statuses []ReadinessStatus
|
||||
|
||||
for _, check := range checks {
|
||||
checkt0 := time.Now()
|
||||
result := checkWithTimeout(check)
|
||||
duration := time.Since(checkt0).Milliseconds()
|
||||
|
||||
details[check.Name] = ReadinessCheckResult{
|
||||
Name: check.Name,
|
||||
Status: result.Status,
|
||||
Message: result.Message,
|
||||
Duration: duration,
|
||||
}
|
||||
statuses = append(statuses, result.Status)
|
||||
}
|
||||
|
||||
return Readiness{
|
||||
Status: worstStatus(statuses),
|
||||
Start: start.UnixMilli(),
|
||||
Duration: time.Since(start).Milliseconds(),
|
||||
Details: details,
|
||||
}
|
||||
}
|
||||
|
||||
// Creates a handler function for readiness HTTP requests.
|
||||
func ReadinessHandler(checks []ReadinessCheck) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
respondWithResult(w, CheckReadiness(checks))
|
||||
}
|
||||
}
|
||||
|
||||
// Runs a readiness check with a timeout.
|
||||
func checkWithTimeout(check ReadinessCheck) ReadinessReturn {
|
||||
timeout := check.Timeout
|
||||
if timeout == 0 {
|
||||
timeout = 5 * time.Second
|
||||
}
|
||||
|
||||
resultCh := make(chan ReadinessReturn, 1)
|
||||
|
||||
go func() {
|
||||
resultCh <- check.Fn()
|
||||
}()
|
||||
|
||||
select {
|
||||
case result := <-resultCh:
|
||||
return result
|
||||
case <-time.After(timeout):
|
||||
msg := "readiness check timed out"
|
||||
return ReadinessReturn{
|
||||
Status: ReadinessStatusFatal,
|
||||
Message: &msg,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func respondWithResult(w http.ResponseWriter, result Readiness) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(result.Status.HTTPStatus())
|
||||
json.NewEncoder(w).Encode(result)
|
||||
}
|
||||
|
||||
// ScheduledReadiness performs periodic readiness checks and stores the latest result.
|
||||
type ScheduledReadiness struct {
|
||||
checks []ReadinessCheck
|
||||
interval time.Duration
|
||||
currentState Readiness
|
||||
ticker *time.Ticker
|
||||
quit chan struct{}
|
||||
}
|
||||
|
||||
// NewScheduledReadiness creates a new ScheduledReadiness instance.
|
||||
func NewScheduledReadiness(checks []ReadinessCheck, interval time.Duration) *ScheduledReadiness {
|
||||
return &ScheduledReadiness{
|
||||
checks: checks,
|
||||
interval: interval,
|
||||
quit: make(chan struct{}),
|
||||
}
|
||||
}
|
||||
|
||||
// Start begins the periodic readiness checks.
|
||||
func (sr *ScheduledReadiness) Start() {
|
||||
sr.ticker = time.NewTicker(sr.interval)
|
||||
go func() {
|
||||
for {
|
||||
select {
|
||||
case <-sr.ticker.C:
|
||||
sr.currentState = CheckReadiness(sr.checks)
|
||||
case <-sr.quit:
|
||||
sr.ticker.Stop()
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// Stop halts the periodic readiness checks.
|
||||
func (sr *ScheduledReadiness) Stop() {
|
||||
close(sr.quit)
|
||||
}
|
||||
|
||||
// GetCurrentState returns the latest readiness state.
|
||||
func (sr *ScheduledReadiness) GetCurrentState() Readiness {
|
||||
return sr.currentState
|
||||
}
|
||||
|
||||
// Creates a handler function for scheduled readiness HTTP requests.
|
||||
func (sr *ScheduledReadiness) ReadinessHandler() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
respondWithResult(w, sr.GetCurrentState())
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@
|
||||
"publishConfig": {
|
||||
"registry": "https://gitea.auvem.com/api/packages/end/npm/"
|
||||
},
|
||||
"version": "0.1.1",
|
||||
"version": "0.1.2",
|
||||
"license": "MIT",
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/** Return type of a readiness check function */
|
||||
export type ReadinessFunctionReturn = {
|
||||
/** Readiness check function return type */
|
||||
export type ReadinessReturn = {
|
||||
/** Status of the readiness check */
|
||||
status: ReadinessStatus;
|
||||
/** Optional message providing additional information about the readiness check */
|
||||
@@ -7,45 +7,47 @@ export type ReadinessFunctionReturn = {
|
||||
};
|
||||
|
||||
/** Function that performs a readiness check */
|
||||
export type ReadinessFunction = (check: ReadinessCheck) => Promise<ReadinessFunctionReturn>;
|
||||
export type ReadinessCheckFn = (check: ReadinessCheck) => Promise<ReadinessReturn>;
|
||||
|
||||
/** Status of a readiness check */
|
||||
export type ReadinessStatus = 'ok' | 'error' | 'degraded';
|
||||
/** Status of the service readiness */
|
||||
export type ReadinessStatus = 'fatal' | 'not_ready' | 'degraded' | 'ready';
|
||||
|
||||
const aggregateStatus = (statuses: ReadinessStatus[]): ReadinessStatus => {
|
||||
if (statuses.includes('error')) return 'error';
|
||||
/** Returns the worst readiness status from a list of statuses. */
|
||||
const worstStatus = (statuses: ReadinessStatus[]): ReadinessStatus => {
|
||||
if (statuses.includes('fatal')) return 'fatal';
|
||||
if (statuses.includes('not_ready')) return 'not_ready';
|
||||
if (statuses.includes('degraded')) return 'degraded';
|
||||
return 'ok';
|
||||
return 'ready';
|
||||
};
|
||||
|
||||
/** Represents a readiness check with an optional timeout */
|
||||
/** Individual readiness check */
|
||||
export type ReadinessCheck = {
|
||||
/** Name of the readiness check */
|
||||
name: string;
|
||||
/** Function that performs the readiness check */
|
||||
fn: ReadinessFunction;
|
||||
fn: ReadinessCheckFn;
|
||||
/** Timeout in milliseconds for the readiness check (default: 5000) */
|
||||
timeout?: number;
|
||||
};
|
||||
|
||||
/** Result of a system readiness check */
|
||||
export type ReadinessResult = {
|
||||
/** System readiness status */
|
||||
export type Readiness = {
|
||||
/**
|
||||
* Status of the system readiness check, aggregated as the worst status
|
||||
* among individual checks. 'unknown' is a special case indicating that
|
||||
* no checks were performed, used by ScheduledReadiness before the first run.
|
||||
* */
|
||||
status: ReadinessStatus | 'unknown';
|
||||
* among individual checks. If no checks have been performed yet, the status
|
||||
* is 'not_ready'.
|
||||
*/
|
||||
status: ReadinessStatus;
|
||||
/** Start time of the system readiness check in milliseconds since the Unix epoch */
|
||||
start: number;
|
||||
/** Duration of the system readiness check in milliseconds */
|
||||
duration: number;
|
||||
/** Details of individual readiness checks */
|
||||
details: ReadinessDetail[];
|
||||
details: ReadinessCheckResult[];
|
||||
};
|
||||
|
||||
/** Detail of an individual readiness check */
|
||||
export type ReadinessDetail = {
|
||||
/** System-generated result from an individual readiness check */
|
||||
export type ReadinessCheckResult = {
|
||||
/** Name of the readiness check */
|
||||
name: string;
|
||||
/** Status of the readiness check */
|
||||
@@ -59,12 +61,12 @@ export type ReadinessDetail = {
|
||||
/**
|
||||
* Performs a readiness check by executing the provided readiness functions.
|
||||
* @param checks - An array of readiness functions to execute.
|
||||
* @returns A Promise that resolves to a ReadinessResult object.
|
||||
* @returns A Promise that resolves to a Readiness object.
|
||||
*/
|
||||
export const readiness = async (checks: ReadinessCheck[]): Promise<ReadinessResult> => {
|
||||
export const readiness = async (checks: ReadinessCheck[]): Promise<Readiness> => {
|
||||
const start = Date.now();
|
||||
const t0 = performance.now();
|
||||
const details: ReadinessDetail[] = [];
|
||||
const details: ReadinessCheckResult[] = [];
|
||||
|
||||
for (const check of checks) {
|
||||
const checkt0 = performance.now();
|
||||
@@ -83,7 +85,7 @@ export const readiness = async (checks: ReadinessCheck[]): Promise<ReadinessResu
|
||||
} catch (err) {
|
||||
details.push({
|
||||
name: check.name,
|
||||
status: 'error',
|
||||
status: 'fatal',
|
||||
message: err instanceof Error ? err.message : String(err),
|
||||
duration: performance.now() - checkt0,
|
||||
});
|
||||
@@ -93,7 +95,7 @@ export const readiness = async (checks: ReadinessCheck[]): Promise<ReadinessResu
|
||||
const duration = performance.now() - t0;
|
||||
|
||||
return {
|
||||
status: aggregateStatus(details.map((d) => d.status)),
|
||||
status: worstStatus(details.map((d) => d.status)),
|
||||
start,
|
||||
duration,
|
||||
details,
|
||||
@@ -104,7 +106,7 @@ export const readiness = async (checks: ReadinessCheck[]): Promise<ReadinessResu
|
||||
* Creates a handler function for readiness HTTP requests. Warning: this runs all
|
||||
* checks on each request and may be slow.
|
||||
* @param checks - An array of readiness functions to execute.
|
||||
* @returns A function that returns a Response object with ReadinessResult in JSON format.
|
||||
* @returns A function that returns a Response object with Readiness in JSON format.
|
||||
*/
|
||||
export const createReadinessHandler = (checks: ReadinessCheck[]): (() => Promise<Response>) => {
|
||||
return async () => {
|
||||
@@ -121,8 +123,8 @@ export class ScheduledReadiness {
|
||||
private interval: number;
|
||||
private started: boolean = false;
|
||||
private timer: NodeJS.Timeout | null = null;
|
||||
private latestResult: ReadinessResult | null = null;
|
||||
private nextResult: Promise<ReadinessResult> | null = null;
|
||||
private latestResult: Readiness | null = null;
|
||||
private nextResult: Promise<Readiness> | null = null;
|
||||
|
||||
/**
|
||||
* Creates an instance of ScheduledReadiness.
|
||||
@@ -165,7 +167,7 @@ export class ScheduledReadiness {
|
||||
}
|
||||
|
||||
/** Gets the next readiness result, waiting if a check is in progress */
|
||||
async getNextResult(): Promise<ReadinessResult | null> {
|
||||
async getNextResult(): Promise<Readiness | null> {
|
||||
if (this.nextResult) {
|
||||
return await this.nextResult;
|
||||
}
|
||||
@@ -173,7 +175,7 @@ export class ScheduledReadiness {
|
||||
}
|
||||
|
||||
/** Gets the latest readiness result without waiting */
|
||||
getResult(): ReadinessResult | null {
|
||||
getResult(): Readiness | null {
|
||||
return this.latestResult;
|
||||
}
|
||||
|
||||
@@ -192,21 +194,21 @@ export class ScheduledReadiness {
|
||||
/**
|
||||
* Creates a handler function for readiness HTTP requests using the latest scheduled result.
|
||||
* Scheduled handler always returns the most recent result, or 'unknown' if no checks have run yet.
|
||||
* @returns A function that returns a Response object with ReadinessResult in JSON format.
|
||||
* @returns A function that returns a Response object with Readiness in JSON format.
|
||||
*/
|
||||
createHandler(): () => Promise<Response> {
|
||||
return async () => {
|
||||
const result = await this.getNextResult();
|
||||
const result = this.getResult();
|
||||
if (!result) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
status: 'unknown',
|
||||
status: 'not_ready',
|
||||
start: Date.now(),
|
||||
duration: 0,
|
||||
details: [],
|
||||
} as ReadinessResult),
|
||||
} as Readiness),
|
||||
{
|
||||
status: httpStatusFromReadiness('unknown'),
|
||||
status: httpStatusFromReadiness('not_ready'),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
},
|
||||
);
|
||||
@@ -217,8 +219,8 @@ export class ScheduledReadiness {
|
||||
}
|
||||
}
|
||||
|
||||
/** Returns a Response object with the given ReadinessResult in JSON format */
|
||||
const respondWithResult = (result: ReadinessResult) => {
|
||||
/** Returns a Response object with the given Readiness in JSON format */
|
||||
const respondWithResult = (result: Readiness) => {
|
||||
return new Response(JSON.stringify(result), {
|
||||
status: httpStatusFromReadiness(result.status),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
@@ -226,11 +228,11 @@ const respondWithResult = (result: ReadinessResult) => {
|
||||
};
|
||||
|
||||
/** Returns the HTTP status code corresponding to a given readiness status */
|
||||
const httpStatusFromReadiness = (status: ReadinessStatus | 'unknown'): number => {
|
||||
if (status === 'ok') return 200;
|
||||
const httpStatusFromReadiness = (status: ReadinessStatus): number => {
|
||||
if (status === 'ready') return 200;
|
||||
if (status === 'degraded') return 200; // 206 could also be suitable, but let's avoid false alarms
|
||||
if (status === 'error') return 503;
|
||||
return 200; // unknown, treat as ok to avoid false alarms
|
||||
if (status === 'fatal') return 503;
|
||||
return 200; // not_ready, treat as ok to avoid false alarms
|
||||
};
|
||||
|
||||
const withTimeout = async <T>(
|
||||
|
||||
Reference in New Issue
Block a user