Skip to content

ghga-de/notification-service

Repository files navigation

tests Coverage Status

Notification Service

The Notification Service (NS) handles notification kafka events.

Description

The Notification Service is a microservice intended to provide general notification capabilities. At this time, notifications are only generated via Kafka events, and they are only issued via email. However, the architecture of the service would allow for the addition of other submission options, such as REST APIs, as well as new notification channels, such as SMS, with relatively little work.

To send an email notification using this service, publish a kafka event conforming to the Notification event schema to the topic configured under "notification_event_topic" (see configuration details below). Because email client authentication is handled by the notification service itself, nothing beyond publishing the event is required.

Typical operation

This service doesn't have a REST API. It is fully stateless and does not require a database. It's a straightforward service running a Kafka consumer that listens for one kind of event. Notification events are picked up by the consumer, validated against the Notification event schema, and sent to the Notifier module. The Notifier looks at the notification event details and determines what to do with it. Right now, this always means sending an email. The information is sent to the SMTP client, where a secure connection is established and the email is dispatched.

Email Templates

In the configuration there are two template requirements: a plaintext email template and an HTML email template. The point of these is to produce consistently formatted emails while keeping the requirements light for microservices trying to send notifications. The templates are both used to make the email. Template variables are denoted with "$", e.g. $recipient_name, and are required to match the notification schema field names defined here. Having both HTML and plaintext means everyone should be able to receive the emails without a problem, and most of the time they should look nice. Because email clients like Outlook, Gmail, etc. have differences in the way they render HTML emails, it is recommended that styling be kept to a minimum or to use a pre-made template where these things have been taken into account.

Installation

We recommend using the provided Docker container.

A pre-build version is available at docker hub:

docker pull ghga/notification-service:2.1.0

Or you can build the container yourself from the ./Dockerfile:

# Execute in the repo's root dir:
docker build -t ghga/notification-service:2.1.0 .

For production-ready deployment, we recommend using Kubernetes, however, for simple use cases, you could execute the service using docker on a single server:

# The entrypoint is preconfigured:
docker run -p 8080:8080 ghga/notification-service:2.1.0 --help

If you prefer not to use containers, you may install the service from source:

# Execute in the repo's root dir:
pip install .

# To run the service:
ns --help

Configuration

Parameters

The service requires the following configuration parameters:

  • db_connection_str (string, format: password, required): MongoDB connection string. Might include credentials. For more information see: https://naiveskill.com/mongodb-connection-string/.

    Examples:

    "mongodb://localhost:27017"
  • db_name (string, required): Name of the database located on the MongoDB server.

    Examples:

    "my-database"
  • log_level (string): The minimum log level to capture. Must be one of: ["CRITICAL", "ERROR", "WARNING", "INFO", "DEBUG", "TRACE"]. Default: "INFO".

  • service_name (string): Default: "ns".

  • service_instance_id (string, required): A string that uniquely identifies this instance across all instances of this service. A globally unique Kafka client ID will be created by concatenating the service_name and the service_instance_id.

    Examples:

    "germany-bw-instance-001"
  • log_format: If set, will replace JSON formatting with the specified string format. If not set, has no effect. In addition to the standard attributes, the following can also be specified: timestamp, service, instance, level, correlation_id, and details. Default: null.

    • Any of

      • string

      • null

    Examples:

    "%(timestamp)s - %(service)s - %(level)s - %(message)s"
    "%(asctime)s - Severity: %(levelno)s - %(msg)s"
  • log_traceback (boolean): Whether to include exception tracebacks in log messages. Default: true.

  • plaintext_email_template (string, required): The plaintext template to use for email notifications.

  • html_email_template (string, required): The HTML template to use for email notifications.

  • from_address (string, format: email, required): The sender's address.

  • smtp_host (string, required): The mail server host to connect to.

  • smtp_port (integer, required): The port for the mail server connection.

  • smtp_auth: . Default: null.

  • use_starttls (boolean): Boolean flag indicating the use of STARTTLS. Default: true.

  • smtp_timeout: The maximum amount of time (in seconds) to wait for a connection to the SMTP server. If set to None, the operation will wait indefinitely. Default: 60.

    • Any of

      • number: Exclusive minimum: 0.0.

      • null

  • notification_event_topic (string, required): Name of the event topic used to track notification events.

    Examples:

    "notifications"
  • notification_event_type (string, required): The type to use for events containing content to be sent.

    Examples:

    "notification"
  • kafka_servers (array, required): A list of connection strings to connect to Kafka bootstrap servers.

    • Items (string)

    Examples:

    [
        "localhost:9092"
    ]
  • kafka_security_protocol (string): Protocol used to communicate with brokers. Valid values are: PLAINTEXT, SSL. Must be one of: ["PLAINTEXT", "SSL"]. Default: "PLAINTEXT".

  • kafka_ssl_cafile (string): Certificate Authority file path containing certificates used to sign broker certificates. If a CA is not specified, the default system CA will be used if found by OpenSSL. Default: "".

  • kafka_ssl_certfile (string): Optional filename of client certificate, as well as any CA certificates needed to establish the certificate's authenticity. Default: "".

  • kafka_ssl_keyfile (string): Optional filename containing the client private key. Default: "".

  • kafka_ssl_password (string, format: password): Optional password to be used for the client private key. Default: "".

  • generate_correlation_id (boolean): A flag, which, if False, will result in an error when trying to publish an event without a valid correlation ID set for the context. If True, the a newly correlation ID will be generated and used in the event header. Default: true.

    Examples:

    true
    false
  • kafka_max_message_size (integer): The largest message size that can be transmitted, in bytes. Only services that have a need to send/receive larger messages should set this. Exclusive minimum: 0. Default: 1048576.

    Examples:

    1048576
    16777216

Definitions

  • SmtpAuthConfig (object): Model to encapsulate SMTP authentication details.

    • username (string, required): The login username or email.

    • password (string, format: password, required): The login password.

Usage:

A template YAML for configurating the service can be found at ./example-config.yaml. Please adapt it, rename it to .ns.yaml, and place it into one of the following locations:

  • in the current working directory were you are execute the service (on unix: ./.ns.yaml)
  • in your home directory (on unix: ~/.ns.yaml)

The config yaml will be automatically parsed by the service.

Important: If you are using containers, the locations refer to paths within the container.

All parameters mentioned in the ./example-config.yaml could also be set using environment variables or file secrets.

For naming the environment variables, just prefix the parameter name with ns_, e.g. for the host set an environment variable named ns_host (you may use both upper or lower cases, however, it is standard to define all env variables in upper cases).

To using file secrets please refer to the corresponding section of the pydantic documentation.

HTTP API

An OpenAPI specification for this service can be found here.

Architecture and Design:

This is a Python-based service following the Triple Hexagonal Architecture pattern. It uses protocol/provider pairs and dependency injection mechanisms provided by the hexkit library.

Testing

The only notable thing about the test setup is that it uses a local test server (tests/fixtures/server.py) via aiosmtpd, which has sort of replaced the old smtpd module. There is a DummyServer, which has an 'expect_email()' method that is used similarly to the expect_events() method from hexkit's kafka testing module. It can perform simple a authentication check so error handling can be tested. When an email is sent to the test server, the connection is closed and the received/expected emails are compared to make sure that the header and body content is intact. This enables testing the flow of sending an email without actually issuing any real emails and without using real credentials.

Development

For setting up the development environment, we rely on the devcontainer feature of VS Code in combination with Docker Compose.

To use it, you have to have Docker Compose as well as VS Code with its "Remote - Containers" extension (ms-vscode-remote.remote-containers) installed. Then open this repository in VS Code and run the command Remote-Containers: Reopen in Container from the VS Code "Command Palette".

This will give you a full-fledged, pre-configured development environment including:

  • infrastructural dependencies of the service (databases, etc.)
  • all relevant VS Code extensions pre-installed
  • pre-configured linting and auto-formatting
  • a pre-configured debugger
  • automatic license-header insertion

Moreover, inside the devcontainer, a convenience commands dev_install is available. It installs the service with all development dependencies, installs pre-commit.

The installation is performed automatically when you build the devcontainer. However, if you update dependencies in the ./pyproject.toml or the ./requirements-dev.txt, please run it again.

License

This repository is free to use and modify according to the Apache 2.0 License.

README Generation

This README file is auto-generated, please see readme_generation.md for details.