From ddd0b50b7e64e6bb5849af0c2b319ab9b80060e8 Mon Sep 17 00:00:00 2001 From: Elliott Sales de Andrade Date: Thu, 18 Aug 2022 03:12:50 -0400 Subject: [PATCH] Add a ping endpoint to webhook service As noted in #25, the webhook was down for some period. The ping endpoint allows some external check to verify that it is running. If Caddy cannot connect to the webhook, it will return 502 instead of 200. --- templates/Caddyfile.j2 | 10 ++++++++++ webhook/test_webhook.py | 9 +++++++++ webhook/webhook.py | 6 ++++++ 3 files changed, 25 insertions(+) diff --git a/templates/Caddyfile.j2 b/templates/Caddyfile.j2 index 5e721fd..d8b4b61 100644 --- a/templates/Caddyfile.j2 +++ b/templates/Caddyfile.j2 @@ -46,6 +46,16 @@ http://{{ caddy.addresses.webhook }} { } } + handle /ping { + reverse_proxy * localhost:1234 { + # Don't leak out internal problems. + @error status 4xx 5xx + handle_response @error { + error 503 + } + } + } + handle { error 404 } diff --git a/webhook/test_webhook.py b/webhook/test_webhook.py index dbe0e13..8668ab7 100644 --- a/webhook/test_webhook.py +++ b/webhook/test_webhook.py @@ -65,6 +65,15 @@ async def test_update_repo(tmp_path_factory): assert dest_commit == src_commit +async def test_ping(aiohttp_client, monkeypatch, tmp_path): + """Test ping always works.""" + monkeypatch.setenv('SITE_DIR', str(tmp_path)) + client = await aiohttp_client(create_app()) + + resp = await client.get('/ping') + assert resp.status == 200 + + async def test_github_webhook_errors(aiohttp_client, monkeypatch, tmp_path): """Test invalid inputs to webhook.""" monkeypatch.setenv('SITE_DIR', str(tmp_path)) diff --git a/webhook/webhook.py b/webhook/webhook.py index 7d4e4f2..5d86d17 100644 --- a/webhook/webhook.py +++ b/webhook/webhook.py @@ -173,6 +173,11 @@ async def github_webhook(request: web.Request): return web.Response(status=200) +async def ping(request: web.Request): + """Respond to a ping, thus verifying the webhook service is alive.""" + return web.Response(status=200) + + def create_app(): """Create the aiohttp app and setup routes.""" site_dir = Path(os.environ.get('SITE_DIR', 'sites')).resolve() @@ -182,6 +187,7 @@ def create_app(): app['site_dir'] = site_dir app.add_routes([ web.post('/gh/{repo}', github_webhook), + web.get('/ping', ping), ]) return app