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

feat: Sentry Ingration #57

Merged
merged 12 commits into from
May 2, 2024
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
5 changes: 5 additions & 0 deletions deployment/server/docker-compose.dev.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ services:
- DATABASE_NAME=${DATABASE_NAME}
- DATABASE_USER=${DATABASE_USER}
- DATABASE_PASSWORD=${DATABASE_PASSWORD}
# Sentry
- SENTRY_DSN=${SENTRY_DSN}
- SENTRY_ENVIRONMENT=local
depends_on:
- db
healthcheck:
Expand All @@ -37,6 +40,8 @@ services:
- VITE_AUTH0_DOMAIN=${VITE_AUTH0_DOMAIN}
- VITE_AUTH0_CLIENT_ID=${VITE_AUTH0_CLIENT_ID}
- VITE_AUTH0_AUDIENCE=${VITE_AUTH0_AUDIENCE}
- VITE_SENTRY_DSN=${VITE_SENTRY_DSN}
- VITE_SENTRY_ENVIRONMENT=local
depends_on:
- api
healthcheck:
Expand Down
5 changes: 5 additions & 0 deletions deployment/server/docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ services:
- DATABASE_NAME=${DATABASE_NAME}
- DATABASE_USER=${DATABASE_USER}
- DATABASE_PASSWORD=${DATABASE_PASSWORD}
# Sentry
- SENTRY_DSN=${SENTRY_DSN}
- SENTRY_ENVIRONMENT=prod
depends_on:
- db
healthcheck:
Expand All @@ -35,6 +38,8 @@ services:
- VITE_AUTH0_DOMAIN=${VITE_AUTH0_DOMAIN}
- VITE_AUTH0_CLIENT_ID=${VITE_AUTH0_CLIENT_ID}
- VITE_AUTH0_AUDIENCE=${VITE_AUTH0_AUDIENCE}
- VITE_SENTRY_DSN=${VITE_SENTRY_DSN}
- VITE_SENTRY_ENVIRONMENT=prod
depends_on:
- api
healthcheck:
Expand Down
23 changes: 23 additions & 0 deletions services/api/carlos/api/app_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,16 @@

from typing import Any

import sentry_sdk
from fastapi import FastAPI
from fastapi.routing import APIRoute
from pydantic.alias_generators import to_camel
from sentry_sdk.integrations.asyncio import AsyncioIntegration
from sentry_sdk.integrations.asyncpg import AsyncPGIntegration
from sentry_sdk.integrations.fastapi import FastApiIntegration
from sentry_sdk.integrations.httpx import HttpxIntegration
from sentry_sdk.integrations.loguru import LoguruIntegration
from sentry_sdk.integrations.sqlalchemy import SqlalchemyIntegration
from starlette.middleware.cors import CORSMiddleware
from starlette.middleware.gzip import GZipMiddleware

Expand All @@ -22,6 +29,8 @@ def create_app(api_settings: CarlosAPISettings | None = None) -> FastAPI:

api_settings = api_settings or CarlosAPISettings()

configure_sentry()

# ensures that the logging is handled via loguru
setup_logging(level=api_settings.LOG_LEVEL)

Expand Down Expand Up @@ -76,3 +85,17 @@ def get_cors_kwargs(api_settings: CarlosAPISettings) -> dict[str, Any]:
"allow_methods": ["*"],
"allow_headers": ["*"],
}


def configure_sentry():
"""Initializes sentry based on environment variables."""
sentry_sdk.init(
integrations=[
AsyncPGIntegration(),
AsyncioIntegration(),
FastApiIntegration(),
HttpxIntegration(),
LoguruIntegration(),
SqlalchemyIntegration(),
],
)
4 changes: 2 additions & 2 deletions services/api/carlos/api/routes/data_routes_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ async def test_get_timeseries_route(
"/data/timeseries",
params={
"timeseriesId": [signal.timeseries_id for signal in driver_signals],
"start_at_utc": "2022-01-01T00:00:00Z",
"end_at_utc": "2022-01-02T00:00:00Z",
"startAtUtc": "2022-01-01T00:00:00Z",
"endAtUtc": "2022-01-02T00:00:00Z",
},
)
assert response.status_code == 200
Expand Down
2 changes: 1 addition & 1 deletion services/api/carlos/api/routes/signals_routes_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ def test_update_device_signal_route(

response = client.put(
f"/signals/{driver_signals[0].timeseries_id}",
json=to_update.dict(),
json=to_update.model_dump(),
)
assert response.is_success, response.text
updated = CarlosDeviceSignal.model_validate(response.json())
Expand Down
54 changes: 53 additions & 1 deletion services/api/poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 1 addition & 4 deletions services/api/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,10 @@ httpx = ">=0.23.1,<1.0.0"
sqlalchemy = {extras = ["mypy"], version = "^2.0.0"}
asyncpg = "^0.29.0"
loguru = "^0.7.2"
sentry-sdk = {extras = ["fastapi", "sqlalchemy", "loguru", "asyncpg", "httpx"], version = "^2.0.1"}

[tool.poetry.group.dev.dependencies]
"devtools" = {path = "../../lib/py_dev_dependencies", develop = true}
"carlos.database" = {path = "../../lib/py_carlos_database", develop = true}
"carlos.edge.interface" = {path = "../../lib/py_edge_interface", develop = true}
"carlos.edge.device" = {path = "../../lib/py_edge_device", develop = true}
"carlos.edge.server" = {path = "../../lib/py_edge_server", develop = true}

[build-system]
requires = ["poetry-core>=1.0.0"]
Expand Down
3 changes: 3 additions & 0 deletions services/device/device/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from loguru import logger

from device.connection import read_connection_settings
from device.sentry import setup_sentry
from device.websocket import DeviceWebsocketClient


Expand All @@ -24,6 +25,8 @@ async def main(): # pragma: no cover

logger.info(f"Starting Carlos device (v{VERSION})...")

setup_sentry()

device_connection = read_connection_settings()
protocol = DeviceWebsocketClient(settings=device_connection)

Expand Down
43 changes: 43 additions & 0 deletions services/device/device/sentry.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
from pathlib import Path

import sentry_sdk
import yaml
from loguru import logger
from pydantic import Field, ValidationError
from pydantic_settings import BaseSettings
from sentry_sdk.integrations.asyncio import AsyncioIntegration
from sentry_sdk.integrations.httpx import HttpxIntegration
from sentry_sdk.integrations.loguru import LoguruIntegration
from sentry_sdk.integrations.sqlalchemy import SqlalchemyIntegration


class SentrySettings(BaseSettings): # pragma: no cover

SENTRY_DSN: str = Field(
...,
description="The DSN tells the SDK where to send the events. If this value "
"is not provided, the SDK will try to read it from the "
"SENTRY_DSN environment variable. If that variable also does not exist, "
"the SDK will just not send any events.",
)


def setup_sentry(): # pragma: no cover

try:
with open(Path.cwd() / "sentry_config", "r") as file:
sentry_config = SentrySettings.model_validate(yaml.safe_load(file))
except FileNotFoundError:
return
except ValidationError:
logger.exception("Failed to validate sentry config.")

sentry_sdk.init(
dsn=sentry_config.SENTRY_DSN,
integrations=[
AsyncioIntegration(),
HttpxIntegration(),
SqlalchemyIntegration(),
LoguruIntegration(),
],
)
62 changes: 61 additions & 1 deletion services/device/poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion services/device/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,11 @@ httpx = "^0.27.0"
# CLI tooling
typer = "^0.12.0"
rich = "^13.7.1"
sentry-sdk = {extras = ["sqlalchemy", "loguru",], version = "^2.0.1"}

[tool.poetry.group.dev.dependencies]
"devtools" = {path = "../../lib/py_dev_dependencies", develop = true}
"carlos.edge.device" = {path = "../../lib/py_edge_device", develop = true}
types-pyyaml = "^6.0.12.20240311"

[tool.poetry.scripts]
carlos-device = "device.cli:main"
Expand Down
1 change: 1 addition & 0 deletions services/frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
"dependencies": {
"@auth0/auth0-vue": "^2.3.3",
"@carbon/icons-vue": "^10.83.1",
"@sentry/vue": "^7.112.2",
"axios": "^1.6.8",
"axios-jwt": "^4.0.2",
"chart.js": "^4.4.2",
Expand Down
5 changes: 5 additions & 0 deletions services/frontend/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ import config from '@/config.ts';
import i18n from '@/plugins/i18n';
import '@/plugins/chartjs';
import '@/plugins/dayjs';
import {
useSentry,
} from '@/plugins/sentry.ts';

const pinia = createPinia();
const app = createApp(App);
Expand All @@ -42,6 +45,8 @@ app.use(
);
app.use(router);

useSentry(app);

app.directive('tooltip', Tooltip);

app.mount('#app');
33 changes: 33 additions & 0 deletions services/frontend/src/plugins/sentry.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import * as Sentry from '@sentry/vue';
import {
App,
} from 'vue';
import config from '@/config';
import packageInfo from '@/../package.json';

export function useSentry(app: App) {
const tracePropagationTargets = [
'localhost',
];
if (config.VITE_APP_API_URL !== undefined) {
tracePropagationTargets.push(config.VITE_APP_API_URL);
}

Sentry.init({
app,
dsn: config.VITE_SENTRY_DSN,
environment: config.VITE_SENTRY_ENVIRONMENT,
release: `Carlos Frontend@${packageInfo.version}`,
integrations: [
Sentry.browserTracingIntegration(),
Sentry.replayIntegration(),
],
// Performance Monitoring
tracesSampleRate: 0.1,
// Set 'tracePropagationTargets' to control for which URLs distributed tracing should be enabled
tracePropagationTargets,
// Session Replay
replaysSessionSampleRate: 0.0,
replaysOnErrorSampleRate: 1.0,
});
}
Loading
Loading