Skip to content
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

Send Check First & Separate Out Errors #43

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 37 additions & 18 deletions custom_components/healthchecksio/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@
from __future__ import annotations

import asyncio
import json
from collections import OrderedDict
from logging import getLogger

import async_timeout
import aiohttp
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.helpers.aiohttp_client import async_get_clientsession
Expand Down Expand Up @@ -125,22 +126,40 @@ async def _test_credentials(
self, api_key, check, self_hosted, site_root, ping_endpoint
):
"""Return true if credentials is valid."""
LOGGER.debug("Testing Credentials")
verify_ssl = not self_hosted or site_root.startswith("https")
session = async_get_clientsession(self.hass, verify_ssl)
timeout10 = aiohttp.ClientTimeout(total=10)
headers = {"X-Api-Key": api_key}
if self_hosted:
check_url = f"{site_root}/{ping_endpoint}/{check}"
else:
check_url = f"https://hc-ping.com/{check}"
await asyncio.sleep(1) # needed for self-hosted instances
try:
verify_ssl = not self_hosted or site_root.startswith("https")
session = async_get_clientsession(self.hass, verify_ssl)
headers = {"X-Api-Key": api_key}
async with async_timeout.timeout(10):
LOGGER.info("Checking API Key")
await session.get(f"{site_root}/api/v1/checks/", headers=headers)

LOGGER.info("Checking Check ID")
if self_hosted:
check_url = f"{site_root}/{ping_endpoint}/{check}"
else:
check_url = f"https://hc-ping.com/{check}"
await asyncio.sleep(1) # needed for self-hosted instances
await session.get(check_url)
check_response = await session.get(check_url, timeout=timeout10)
except (TimeoutError, aiohttp.ClientError):
LOGGER.exception("Could Not Send Check")
return False
else:
if check_response.ok:
LOGGER.debug("Send Check HTTP Status Code: %s", check_response.status)
else:
LOGGER.error("Send Check HTTP Status Code: %s", check_response.status)
return False
try:
request = await session.get(
f"{site_root}/api/v1/checks/", headers=headers, timeout=timeout10
)
except (TimeoutError, aiohttp.ClientError):
LOGGER.exception("Could Not Update Data")
return False
except (ValueError, json.decoder.JSONDecodeError):
LOGGER.exception("Data JSON Decode Error")
return False
else:
if not request.ok:
LOGGER.error("Got Data HTTP Status Code: %s", request.status)
return False
LOGGER.debug("Got Data HTTP Status Code: %s", request.status)
return True
except Exception: # pylint: disable=broad-except
LOGGER.exception("Unknown error occurred")
return False
22 changes: 9 additions & 13 deletions custom_components/healthchecksio/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

from __future__ import annotations

import asyncio
from logging import getLogger
from typing import TYPE_CHECKING, Any

Expand Down Expand Up @@ -50,22 +49,11 @@ def __init__(

async def _async_update_data(self) -> dict[str, Any]:
"""Update data."""
try:
data = await self._session.get(
f"{self._site_root}/api/v1/checks/",
headers={"X-Api-Key": self._api_key},
timeout=ClientTimeout(total=10),
)
except Exception as error:
raise UpdateFailed(error) from error

check_url = (
f"https://hc-ping.com/{self._check_id}"
if not self._self_hosted
else f"{self._site_root}/{self._ping_endpoint}/{self._check_id}"
)
if self._self_hosted:
await asyncio.sleep(1) # needed for self-hosted instances

try:
await self._session.get(
Expand All @@ -75,4 +63,12 @@ async def _async_update_data(self) -> dict[str, Any]:
except Exception:
LOGGER.exception("Could not ping")

return await data.json()
try:
data = await self._session.get(
f"{self._site_root}/api/v1/checks/",
headers={"X-Api-Key": self._api_key},
timeout=ClientTimeout(total=10),
)
return await data.json()
except Exception as error:
raise UpdateFailed(error) from error