Skip to content

Commit

Permalink
ヘルスチェック用APIの追加。
Browse files Browse the repository at this point in the history
  • Loading branch information
Fumika Koyama committed Oct 20, 2023
1 parent ec6b223 commit 8566924
Show file tree
Hide file tree
Showing 4 changed files with 154 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Diagnostics.HealthChecks;

namespace Dressca.Web.Controllers;

/// <summary>
/// ヘルスチェック用のコントローラー。
/// </summary>
[Route("api/health")]
[ApiController]
public class HealthController : ControllerBase
{
private readonly HealthCheckService healthCheckService;

/// <summary>
/// コンストラクター。
/// </summary>
/// <param name="healthCheckService">ヘルスチェックサービス。</param>
public HealthController(HealthCheckService healthCheckService)
{
this.healthCheckService = healthCheckService;
}

/// <summary>
/// ヘルスチェックの結果を返します。
/// </summary>
/// <returns>ヘルスチェックの結果。</returns>
[HttpGet]
public async Task<ActionResult> Get()
{
HealthReport report = await this.healthCheckService.CheckHealthAsync();

var result = new
{
status = report.Status.ToString(),
result = report.Entries
.Select(entry => new
{
name = entry.Key,
status = entry.Value.Status.ToString(),
description = entry.Value.Description?.ToString(),
data = entry.Value.Data,
exception = new
{
source = entry.Value.Exception?.Source,
message = entry.Value.Exception?.Message,
stackTrace = entry.Value.Exception?.StackTrace,
},
}),
};
return report.Status == HealthStatus.Healthy ? this.Ok(result) : this.StatusCode((int)HttpStatusCode.ServiceUnavailable, result);
}

/// <summary>
/// ヘルスチェックの結果を返します。
/// </summary>
/// <returns>ヘルスチェックの結果。</returns>
[HttpHead]
public async Task<ActionResult> Head()
{
HealthReport report = await this.healthCheckService.CheckHealthAsync();
return report.Status == HealthStatus.Healthy ? this.Ok() : this.StatusCode((int)HttpStatusCode.ServiceUnavailable);
}
}
41 changes: 41 additions & 0 deletions samples/Dressca/dressca-backend/src/Dressca.Web/DbHealthCheck.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
using System.Data.Common;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Diagnostics.HealthChecks;

namespace Dressca.Web;

/// <summary>
/// データベースのヘルスチェックを行うクラスです。
/// </summary>
public class DbHealthCheck : IHealthCheck
{
private string connectionString = @"Server=(localdb)\mssqllocaldb;Database=Dressca.Eshop;Integrated Security=True";

/// <summary>
/// データベースへの接続を確認します。
/// </summary>
/// <param name="context">ヘルスチェックコンテキスト。</param>
/// <param name="cancellationToken">キャンセルトークン。</param>
/// <returns>ヘルスチェックの結果。</returns>
public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
{
using (var connection = new SqlConnection(this.connectionString))
{
try
{
await connection.OpenAsync(cancellationToken);

var command = connection.CreateCommand();
command.CommandText = "SELECT 1";

await command.ExecuteNonQueryAsync(cancellationToken);
}
catch (DbException ex)
{
return new HealthCheckResult(status: context.Registration.FailureStatus, exception: ex);
}
}

return HealthCheckResult.Healthy();
}
}
4 changes: 4 additions & 0 deletions samples/Dressca/dressca-backend/src/Dressca.Web/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using Dressca.ApplicationCore;
using Dressca.EfInfrastructure;
using Dressca.Store.Assets.StaticFiles;
using Dressca.Web;
using Dressca.Web.Baskets;
using Dressca.Web.Controllers;
using Dressca.Web.Mapper;
Expand Down Expand Up @@ -67,6 +68,9 @@
});
}

builder.Services.AddHealthChecks()
.AddCheck<DbHealthCheck>("DbHealthCheck");

var app = builder.Build();

if (app.Environment.IsDevelopment())
Expand Down
47 changes: 44 additions & 3 deletions samples/Dressca/dressca-backend/src/Dressca.Web/dressca-api.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"x-generator": "NSwag v13.18.2.0 (NJsonSchema v10.8.0.0 (Newtonsoft.Json v13.0.0.0))",
"x-generator": "NSwag v13.19.0.0 (NJsonSchema v10.9.0.0 (Newtonsoft.Json v13.0.0.0))",
"openapi": "3.0.0",
"info": {
"title": "Dressca Web API",
Expand All @@ -26,8 +26,7 @@
"required": true,
"description": "アセットコード。",
"schema": {
"type": "string",
"nullable": true
"type": "string"
},
"x-position": 1
}
Expand Down Expand Up @@ -332,6 +331,48 @@
}
}
},
"/api/health": {
"get": {
"tags": [
"Health"
],
"summary": "ヘルスチェックの結果を返します。",
"operationId": "Health_Get",
"responses": {
"200": {
"description": "ヘルスチェックの結果。",
"content": {
"application/octet-stream": {
"schema": {
"type": "string",
"format": "binary"
}
}
}
}
}
},
"head": {
"tags": [
"Health"
],
"summary": "ヘルスチェックの結果を返します。",
"operationId": "Health_Head",
"responses": {
"200": {
"description": "ヘルスチェックの結果。",
"content": {
"application/octet-stream": {
"schema": {
"type": "string",
"format": "binary"
}
}
}
}
}
}
},
"/api/orders/{orderId}": {
"get": {
"tags": [
Expand Down

0 comments on commit 8566924

Please sign in to comment.