Skip to content
This repository has been archived by the owner on Oct 11, 2024. It is now read-only.

Commit

Permalink
refactor: Refactors analytics into telemetry module (#20)
Browse files Browse the repository at this point in the history
* refactor: Refactored telemetry

* docs: Fixes codecov badge in README

* refactor: Renamed constructor arg
  • Loading branch information
frgfm authored Oct 30, 2023
1 parent fa58a53 commit 8f9b4ec
Show file tree
Hide file tree
Showing 6 changed files with 29 additions and 29 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
</a>
<a href="https://www.codacy.com/gh/quack-ai/contribution-api/dashboard?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=quack-ai/contribution-api&amp;utm_campaign=Badge_Grade"><img src="https://app.codacy.com/project/badge/Grade/f8b24d4f9f674ef487b0889b2aa90e9c"/></a>
<a href="https://codecov.io/gh/quack-ai/contribution-api">
<img src="https://img.shields.io/codecov/c/github/quack-ai/contribution-api.svg?logo=codecov&style=flat-square" alt="Test coverage percentage">
<img src="https://img.shields.io/codecov/c/github/quack-ai/contribution-api.svg?logo=codecov&style=flat-square&token=fkT0jQefhO" alt="Test coverage percentage">
</a>
</p>
<p align="center">
Expand Down
10 changes: 5 additions & 5 deletions src/app/api/api_v1/endpoints/guidelines.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@
from fastapi import APIRouter, Depends, Path, Security, status

from app.api.dependencies import get_current_user, get_guideline_crud
from app.core.analytics import analytics_client
from app.crud import GuidelineCRUD
from app.models import Guideline, UserScope
from app.schemas.guidelines import ContentUpdate, GuidelineCreate, GuidelineEdit, OrderUpdate
from app.services.telemetry import telemetry_client

router = APIRouter()

Expand All @@ -24,7 +24,7 @@ async def create_guideline(
user=Security(get_current_user, scopes=[UserScope.USER, UserScope.ADMIN]),
) -> Guideline:
guideline = await guidelines.create(payload)
analytics_client.capture(user.id, event="guideline-creation", properties={"repo_id": payload.repo_id})
telemetry_client.capture(user.id, event="guideline-creation", properties={"repo_id": payload.repo_id})
return guideline


Expand Down Expand Up @@ -53,7 +53,7 @@ async def update_guideline_content(
user=Security(get_current_user, scopes=[UserScope.USER, UserScope.ADMIN]),
) -> Guideline:
guideline = await guidelines.update(guideline_id, ContentUpdate(**payload.dict(), updated_at=datetime.utcnow()))
analytics_client.capture(user.id, event="guideline-content", properties={"repo_id": guideline.repo_id})
telemetry_client.capture(user.id, event="guideline-content", properties={"repo_id": guideline.repo_id})
return guideline


Expand All @@ -65,7 +65,7 @@ async def update_guideline_order(
user=Security(get_current_user, scopes=[UserScope.USER, UserScope.ADMIN]),
) -> Guideline:
guideline = await guidelines.update(guideline_id, OrderUpdate(order=order_idx, updated_at=datetime.utcnow()))
analytics_client.capture(user.id, event="guideline-order", properties={"repo_id": guideline.repo_id})
telemetry_client.capture(user.id, event="guideline-order", properties={"repo_id": guideline.repo_id})
return guideline


Expand All @@ -77,4 +77,4 @@ async def delete_guideline(
) -> None:
guideline = cast(Guideline, await guidelines.get(guideline_id, strict=True))
await guidelines.delete(guideline_id)
analytics_client.capture(user.id, event="guideline-deletion", properties={"repo_id": guideline.repo_id})
telemetry_client.capture(user.id, event="guideline-deletion", properties={"repo_id": guideline.repo_id})
10 changes: 5 additions & 5 deletions src/app/api/api_v1/endpoints/login.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,13 @@
from pydantic import HttpUrl

from app.api.dependencies import get_user_crud
from app.core.analytics import analytics_client
from app.core.config import settings
from app.core.security import create_access_token, hash_password, verify_password
from app.crud import UserCRUD
from app.models import UserScope
from app.schemas.login import GHAccessToken, GHToken, GHTokenRequest, Token, TokenRequest
from app.schemas.users import UserCreation
from app.services.telemetry import telemetry_client

router = APIRouter()

Expand Down Expand Up @@ -72,7 +72,7 @@ async def login_with_creds(
# create access token using user user_id/user_scopes
token_data = {"sub": str(user.id), "scopes": user.scope.split()}
token = await create_access_token(token_data, settings.ACCESS_TOKEN_UNLIMITED_MINUTES)
analytics_client.capture(user.id, event="user-login", properties={"login": user.login})
telemetry_client.capture(user.id, event="user-login", properties={"login": user.login})

return Token(access_token=token, token_type="bearer") # nosec B106 # noqa S106

Expand Down Expand Up @@ -101,7 +101,7 @@ async def login_with_github_token(
user = await users.get(gh_user["id"], strict=False)
# Register if non existing
if user is None:
analytics_client.identify(
telemetry_client.identify(
gh_user["id"],
properties={
"login": gh_user["login"],
Expand All @@ -118,11 +118,11 @@ async def login_with_github_token(
scope=UserScope.USER,
)
)
analytics_client.capture(user.id, event="user-creation", properties={"login": gh_user["login"]})
telemetry_client.capture(user.id, event="user-creation", properties={"login": gh_user["login"]})

# create access token using user user_id/user_scopes
token_data = {"sub": str(user.id), "scopes": user.scope.split()}
token = await create_access_token(token_data, settings.ACCESS_TOKEN_UNLIMITED_MINUTES)
analytics_client.capture(user.id, event="user-login", properties={"login": user.login})
telemetry_client.capture(user.id, event="user-login", properties={"login": user.login})

return Token(access_token=token, token_type="bearer") # nosec B106 # noqa S106
16 changes: 8 additions & 8 deletions src/app/api/api_v1/endpoints/repos.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@
from fastapi import APIRouter, Depends, HTTPException, Path, Security, status

from app.api.dependencies import get_current_user, get_guideline_crud, get_repo_crud
from app.core.analytics import analytics_client
from app.crud import GuidelineCRUD, RepositoryCRUD
from app.models import Guideline, Repository, User, UserScope
from app.schemas.guidelines import OrderUpdate
from app.schemas.repos import GuidelineOrder, RepoCreate, RepoCreation, RepoUpdate
from app.services.telemetry import telemetry_client

router = APIRouter()

Expand All @@ -29,13 +29,13 @@ async def create_repo(
if entry is not None:
await repos.update(payload.id, RepoUpdate(removed_at=None))
entry.removed_at = None
analytics_client.capture(
telemetry_client.capture(
user.id, event="repo-enable", properties={"repo_id": payload.id, "full_name": payload.full_name}
)
return entry

repo = await repos.create(RepoCreation(**payload.dict(), installed_by=user.id))
analytics_client.capture(
telemetry_client.capture(
user.id, event="repo-creation", properties={"repo_id": payload.id, "full_name": payload.full_name}
)
return repo
Expand All @@ -56,7 +56,7 @@ async def fetch_repos(
user=Security(get_current_user, scopes=[UserScope.USER, UserScope.ADMIN]),
) -> List[Repository]:
entries = await repos.fetch_all() if user.scope == UserScope.ADMIN else await repos.fetch_all(("owner_id", user.id))
analytics_client.capture(user.id, event="repo-fetch")
telemetry_client.capture(user.id, event="repo-fetch")
return [elt for elt in entries]


Expand All @@ -81,7 +81,7 @@ async def reorder_guidelines(
await guidelines.update(guideline_id, OrderUpdate(order=order_idx, updated_at=datetime.utcnow()))
for order_idx, guideline_id in enumerate(payload.guideline_ids)
]
analytics_client.capture(user.id, event="guideline-order", properties={"repo_id": repo_id})
telemetry_client.capture(user.id, event="guideline-order", properties={"repo_id": repo_id})
return guideline_list


Expand All @@ -92,7 +92,7 @@ async def disable_repo(
user=Security(get_current_user, scopes=[UserScope.USER, UserScope.ADMIN]),
) -> Repository:
repo = await repos.update(repo_id, RepoUpdate(removed_at=datetime.utcnow()))
analytics_client.capture(user.id, event="repo-disable", properties={"repo_id": repo_id})
telemetry_client.capture(user.id, event="repo-disable", properties={"repo_id": repo_id})
return repo


Expand All @@ -103,7 +103,7 @@ async def enable_repo(
user=Security(get_current_user, scopes=[UserScope.USER, UserScope.ADMIN]),
) -> Repository:
repo = await repos.update(repo_id, RepoUpdate(removed_at=None))
analytics_client.capture(user.id, event="repo-enable", properties={"repo_id": repo_id})
telemetry_client.capture(user.id, event="repo-enable", properties={"repo_id": repo_id})
return repo


Expand All @@ -114,7 +114,7 @@ async def delete_repo(
user=Security(get_current_user, scopes=[UserScope.ADMIN]),
) -> None:
await repos.delete(repo_id)
analytics_client.capture(user.id, event="repo-delete", properties={"repo_id": repo_id})
telemetry_client.capture(user.id, event="repo-delete", properties={"repo_id": repo_id})


@router.get("/{repo_id}/guidelines", status_code=status.HTTP_200_OK)
Expand Down
6 changes: 3 additions & 3 deletions src/app/api/api_v1/endpoints/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@
from fastapi import APIRouter, Depends, Path, Security, status

from app.api.dependencies import get_current_user, get_user_crud
from app.core.analytics import analytics_client
from app.core.security import hash_password
from app.crud import UserCRUD
from app.models import User, UserScope
from app.schemas.users import Cred, CredHash, UserCreate, UserCreation
from app.services.telemetry import telemetry_client

router = APIRouter()

Expand All @@ -29,7 +29,7 @@ async def create_user(
user = await users.create(
UserCreation(id=payload.id, login=payload.login, hashed_password=pwd, scope=payload.scope)
)
analytics_client.capture(payload.id, event="user-creation", properties={"login": payload.login})
telemetry_client.capture(payload.id, event="user-creation", properties={"login": payload.login})
return user


Expand Down Expand Up @@ -68,4 +68,4 @@ async def delete_user(
user=Security(get_current_user, scopes=[UserScope.ADMIN]),
) -> None:
await users.delete(user_id)
analytics_client.capture(user_id, event="user-deletion", properties={"login": user.login})
telemetry_client.capture(user_id, event="user-deletion", properties={"login": user.login})
14 changes: 7 additions & 7 deletions src/app/core/analytics.py → src/app/services/telemetry.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,14 @@

logger = logging.getLogger("uvicorn.error")

__all__ = ["analytics_client"]
__all__ = ["telemetry_client"]


class AnalyticsClient:
def __init__(self, ph_api_key: Union[str, None] = None) -> None:
self.is_enabled = isinstance(ph_api_key, str)
if isinstance(ph_api_key, str):
self.ph_client = Posthog(project_api_key=ph_api_key, host="https://eu.posthog.com")
class TelemetryClient:
def __init__(self, api_key: Union[str, None] = None) -> None:
self.is_enabled = isinstance(api_key, str)
if isinstance(api_key, str):
self.ph_client = Posthog(project_api_key=api_key, host="https://eu.posthog.com")
logger.info("PostHog enabled")

def capture(self, *args, **kwargs) -> None:
Expand All @@ -31,4 +31,4 @@ def identify(self, *args, **kwargs) -> None:
self.ph_client.identify(*args, **kwargs)


analytics_client = AnalyticsClient(ph_api_key=settings.POSTHOG_KEY)
telemetry_client = TelemetryClient(api_key=settings.POSTHOG_KEY)

0 comments on commit 8f9b4ec

Please sign in to comment.