Skip to content

Commit

Permalink
init webhook listener service
Browse files Browse the repository at this point in the history
  • Loading branch information
TurkerKoc committed Nov 11, 2024
1 parent e075d09 commit 6dae611
Show file tree
Hide file tree
Showing 12 changed files with 566 additions and 0 deletions.
164 changes: 164 additions & 0 deletions server/webhook-listener/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock

# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
.pdm.toml
.pdm-python
.pdm-build/

# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/

# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
.idea/

/nats_data
9 changes: 9 additions & 0 deletions server/webhook-listener/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
FROM python:3.12

WORKDIR /code

COPY requirements.txt /code/requirements.txt
RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
COPY ./app /code/app

CMD ["fastapi", "run", "app/main.py", "--port", "4200"]
86 changes: 86 additions & 0 deletions server/webhook-listener/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
# WebHook Listener

## Overview

A service to listen GitHub webhooks and publish the data to NATS JetStream.

## Setup

### Prerequisites

- **Python 3.x.x**
- **Docker** for containerization

## Environment Variables

- `NATS_URL`: NATS server URL
- `NATS_AUTH_TOKEN`: Authorization token for NATS server
- `WEBHOOK_SECRET`: HMAC secret for verifying GitHub webhooks

If you are using docker compose, you don't need to set NATS_URL for local development.

Generate an AUTH TOKEN and Set the environment variable:

```bash
export NATS_AUTH_TOKEN=$(openssl rand -hex 48)
```

Set Webhook secret
```bash
export WEBHOOK_SECRET=
```

## Running with Docker Compose

Build and run with Docker Compose:

```bash
docker-compose up --build
```

Service ports:
- **Webhook Service**: `4200`
- **NATS Server**: `4222`


## Usage

Configure your GitHub webhooks to POST to:

```
https://<server>:4200/github
```

### Event Handling

Events are published to NATS with the subject:

```
github.<owner>.<repo>.<event_type>
```



## Setup for Local Development
### Installation

Install dependencies:

```bash
pip install -r requirements.txt
```

### Running Service


```bash
fastapi dev #For Development
fastapi run #For Production
```

### Important Notes

- The service automatically sets up a NATS JetStream stream named `github` to store events.
- Ensure your firewall allows traffic on port 4222 (NATS).
- Authentication tokens are crucial for securing the NATS server and ensuring only authorized clients can connect.
- The webhook listener service connects to the NATS server like any other client using the specified URL and token.
Empty file.
Empty file.
12 changes: 12 additions & 0 deletions server/webhook-listener/app/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
from pydantic_settings import BaseSettings


class Settings(BaseSettings):
NATS_URL: str = "localhost"
NATS_AUTH_TOKEN: str = ""
WEBHOOK_SECRET: str = ""

class Config:
env_file = ".env"

settings = Settings()
32 changes: 32 additions & 0 deletions server/webhook-listener/app/logger.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import logging
import sys
from typing import Any


logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
stream_handler = logging.StreamHandler(sys.stdout)
log_formatter = logging.Formatter("%(levelname)s:\t %(message)s")
stream_handler.setFormatter(log_formatter)
logger.addHandler(stream_handler)

logger.info("Logger initialized")


class EndpointFilter(logging.Filter):
def __init__(
self,
path: str,
*args: Any,
**kwargs: Any,
):
super().__init__(*args, **kwargs)
self._path = path

def filter(self, record: logging.LogRecord) -> bool:
return record.getMessage().find(self._path) == -1

uvicorn_logger = logging.getLogger("uvicorn.access")
uvicorn_logger.addFilter(EndpointFilter(path="/health"))

uvicorn_error = logging.getLogger("uvicorn.error")
Loading

0 comments on commit 6dae611

Please sign in to comment.