Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Code Reviews

Welcome to Software Development on Codidact!

Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.

Post History

71%
+3 −0
Code Reviews Health checks with caching in ASP.NET Core

private readonly int _checkInterval; What are the units? I have to search for usages to find out. I strongly favour using TimeSpan instead of int. private static readonly SemaphoreS...

posted 1y ago by Peter Taylor‭

Answer
#1: Initial revision by user avatar Peter Taylor‭ · 2023-01-30T17:26:50Z (about 1 year ago)
> 		private readonly int _checkInterval;

What are the units? I have to search for usages to find out. I strongly favour using `TimeSpan` instead of `int`.

---

> 		private static readonly SemaphoreSlim Semaphore = new(1);

Is it essential that the semaphore be shared between all health checks? That conditions possible solutions to the problem raised in the question.

---

> 		public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context,
> 			CancellationToken cancellationToken = default)
> 		{
> 			if (!IsCacheExpired())
> 				return LastHealthCheckResult;
> 
> 			try
> 			{
> 				await Semaphore.WaitAsync(cancellationToken);
> 
> 				if (IsCacheExpired())
> 				{
> 					LastCheckTime = DateTime.UtcNow;
> 					await CheckService();
> 				}
> 			}
> 			finally
> 			{
> 				Semaphore.Release();
> 			}
> 
> 			return LastHealthCheckResult;
> 		}

I assume this is the method defined in `IHealthCheck`, and there are two things about it which I find questionable.

1. Is there a reason for choosing inheritance over composition? I.e. instead of calling an abstract `CheckService`, why not call `CheckHealthAsync` on a wrapped `IHealthService`? (I recognise that the answer might be "constraints of the IoC library").
2. Is the double-checked locking with both `return`s outside the critical block actually safe? (It may be, but I'm wary and would like to see a comment justifying it).

---

> 		protected abstract Task CheckService();

Not `CheckServiceAsync`?

---

>     protected HealthCheckResult LastHealthCheckResult { get; set; } = HealthCheckResult.Healthy();
> 
>     ...
> 
>     protected abstract DateTime LastCheckTime { get; set; }

`LastCheckTime` is done like this because otherwise it doesn't get persisted. But that surely means that `LastHealthCheckResult` doesn't get persisted, so if the test against `LastCheckTime` determines that it's not necessary to perform the test again it will always return `Healthy()`. I'm not sure whether the bug is in the implementation or the use of *Cached* in the name, but one of them is wrong.

---

> What I don't like is the way I am handling the last check datetime, which must be added as a static property within each implementing class. Any ideas about how to improve this part?

Sure: move the static property up to `CachedHealthCheckBase`. I see multiple options, although their elegance may be debatable:

1. If you want to stick to inheritance, use F-bounded polymorphism: `CachedHealthCheckBase<T> where T : CachedHealthCheckBase<T>`. Now each concrete implementation has a different base class. I concede that it's somewhat inelegant to create a type parameter which is then never used in the source code.
2. Favour composition over inheritance and use a static `Dictionary<TKey, (DateTime, HealthCheckResult)` where `TKey` is either a string passed in to the constructor, a type passed into the constructor, or `GetType()` called on the wrapped check. This would force you not to use double-checked locking and to move everything into the critical region so that access to the dictionary is thread-safe.
3. Hybrid: use composition with polymorphism:

       public class CachedHealthCheck<THealthCheck> : IHealthCheck
           where THealthCheck : IHealthCheck
       {
           ...
           public CachedHealthCheck(THealthCheck uncachedCheck, TimeSpan cacheInterval)