-
Notifications
You must be signed in to change notification settings - Fork 1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add DependenciesHealthcheck dependency #17
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Validating CODEOWNERS rules …
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1 @@ | ||
* @RB387 @jerry-git | ||
* @RB387 @jerry-git @erhosen |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,73 @@ | ||
import asyncio | ||
from asyncio import Future | ||
from contextlib import suppress | ||
from dataclasses import dataclass | ||
from typing import Any, Protocol | ||
|
||
from magic_di import Connectable, ConnectableProtocol, DependencyInjector | ||
|
||
|
||
class PingableProtocol(ConnectableProtocol, Protocol): | ||
async def __ping__(self) -> None: ... | ||
|
||
|
||
@dataclass | ||
class DependenciesHealthcheck(Connectable): | ||
""" | ||
Injectable Healthcheck component that pings all injected dependencies | ||
that implement the PingableProtocol | ||
|
||
Example usage: | ||
|
||
```python | ||
from app.components.services.health import DependenciesHealthcheck | ||
|
||
async def main(redis: Redis, deps_healthcheck: DependenciesHealthcheck) -> None: | ||
await deps_healthcheck.ping_dependencies() # redis will be pinged if it has method __ping__ | ||
|
||
inject_and_run(main) | ||
``` | ||
""" | ||
|
||
injector: DependencyInjector | ||
|
||
async def ping_dependencies(self, max_concurrency: int = 1) -> None: | ||
""" | ||
Ping all dependencies that implement the PingableProtocol | ||
|
||
:param max_concurrency: Maximum number of concurrent pings | ||
""" | ||
tasks: set[Future[Any]] = set() | ||
|
||
try: | ||
for dependency in self.injector.get_dependencies_by_interface(PingableProtocol): | ||
future = asyncio.ensure_future(self.ping(dependency)) | ||
tasks.add(future) | ||
|
||
if len(tasks) >= max_concurrency: | ||
tasks, _ = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED) | ||
|
||
if tasks: | ||
await asyncio.gather(*tasks) | ||
tasks = set() | ||
|
||
finally: | ||
for task in tasks: | ||
task.cancel() | ||
|
||
if tasks: | ||
with suppress(asyncio.CancelledError): | ||
await asyncio.gather(*tasks) | ||
|
||
async def ping(self, dependency: PingableProtocol) -> None: | ||
""" | ||
Ping a single dependency | ||
|
||
:param dependency: Dependency to ping | ||
""" | ||
dependency_name = dependency.__class__.__name__ | ||
self.injector.logger.debug("Pinging dependency %s...", dependency_name) | ||
|
||
await dependency.__ping__() | ||
|
||
self.injector.logger.debug("Dependency %s is healthy", dependency_name) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Would it be beneficial if this would return information about which ones failed (and which one succeeded)? Then it would be possible to include that information in the response of the healthcheck endpoint. At minimum, I think there could be some logging inside this method about failures.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Currently one of our services uses this approach: each dependency (such as redis, mongo or kafka-consumer) implements a ping method, that might raise an exception. Each of those pings has they own set of exceptions (e.g.,
ConnectionFailure
,NetworkTimeout
,OperationFailure
for MongoDB), and we’ve intentionally decided not to catch them.This approach ensures that in case of fire, we get a complete stack trace in the logs, making it easier to debug what happened.
And it also leads to 500 error status code for a typical FastAPI/Starlette server. Since these health checks are primarily designed for Kubernetes - correct status code is basically the only thing that matters
What do you think about it?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hmm. Do we have any case where we need to know which dependencies are healthy or not?
Usually we only want to know if everything is healthy.
That’s a good point. I added debug logging, but I decided not to log failures since they are raised to user and user can catch them and log if needed.
But, what I’m thinking about is, do we need the ignore_exceptions argument? To ignore some concrete exceptions that are raised by some dependencies
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yeah, I guess it makes sense, at least in K8s (probes) use cases. I was just thinking that peeps in the wider community might have also non-K8s use cases in which it might be beneficial to know which ones failed. Anyway, I guess this will be sufficient for majority.
At least I can't think of a real world use case in which one would like to check the healthiness of all dependencies but ignore some 🤔