-
Notifications
You must be signed in to change notification settings - Fork 28
Notifications backend #1904
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
Open
davidwaroquiers
wants to merge
12
commits into
datalab-org:main
Choose a base branch
from
Matgenix:dw/notifications_backend
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Notifications backend #1904
Changes from 8 commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
8a0faa3
Added backend model and routes for notifications.
davidwaroquiers 6b781f0
Merge branch 'main' into dw/notifications_backend
davidwaroquiers f978bcb
Merge branch 'main' into dw/notifications_backend
davidwaroquiers 8db10f8
Merge branch 'main' into dw/notifications_backend
davidwaroquiers 08985a6
Some fixes after review.
davidwaroquiers b40ec15
Fixed possible problem with failure to send multiple notifications at
davidwaroquiers bd0b224
More changes based on Guido's review.
davidwaroquiers 1236de2
Removed create_notification function.
davidwaroquiers a89f2e7
Renamed variables to prevent shadowing name from outer scope.
davidwaroquiers 7c089f9
Narrowed down the exception for transaction support test.
davidwaroquiers c8d4027
Removed notification_id from delete_notification and
davidwaroquiers 12efc5f
Raising NotFound instead of calling abort(404) when notifications are
davidwaroquiers File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,116 @@ | ||
| from datetime import datetime, timezone | ||
| from enum import Enum | ||
|
|
||
| from pydantic import BaseModel, Field, root_validator | ||
|
|
||
| from pydatalab.models.entries import Entry | ||
| from pydatalab.models.utils import JSON_ENCODERS, PyObjectId | ||
|
|
||
|
|
||
| class NotificationLevel(str, Enum): | ||
| LOW = "low" | ||
| NORMAL = "normal" | ||
| IMPORTANT = "important" | ||
| URGENT = "urgent" | ||
| CRITICAL = "critical" | ||
|
|
||
| @property | ||
| def priority(self) -> int: | ||
| return { | ||
| NotificationLevel.LOW: 10, | ||
| NotificationLevel.NORMAL: 20, | ||
| NotificationLevel.IMPORTANT: 30, | ||
| NotificationLevel.URGENT: 40, | ||
| NotificationLevel.CRITICAL: 50, | ||
| }[self] | ||
|
|
||
|
|
||
| class NotificationGroupPolicy(str, Enum): | ||
| ONCE = "once" | ||
| WINDOW = "window" | ||
|
|
||
|
|
||
| class NotificationGrouping(BaseModel): | ||
| """Rules for grouping repeated notification occurrences.""" | ||
|
|
||
| key: str = Field( | ||
| ..., | ||
| min_length=1, | ||
| max_length=500, | ||
| description="Stable key used to group repeated notifications from the same thing.", | ||
| ) | ||
| policy: NotificationGroupPolicy = Field( | ||
| NotificationGroupPolicy.WINDOW, | ||
| description="How repeated notification occurrences should be grouped.", | ||
| ) | ||
| window_seconds: int | None = Field( | ||
| 86400, | ||
| ge=1, | ||
| description=( | ||
| "Minimum interval before a grouped notification can create a new notification document." | ||
| ), | ||
| ) | ||
| max_occurrences: int = Field( | ||
| 100, | ||
| ge=1, | ||
| description="Maximum number of occurrences before a new notification document is created.", | ||
| ) | ||
|
|
||
| @root_validator | ||
| def validate_grouping_policy(cls, values): | ||
| policy = NotificationGroupPolicy(values.get("policy")) | ||
| if policy == NotificationGroupPolicy.WINDOW and values.get("window_seconds") is None: | ||
| raise ValueError("window_seconds must be provided for window grouping.") | ||
| if policy == NotificationGroupPolicy.ONCE: | ||
| values["window_seconds"] = None | ||
| return values | ||
|
|
||
| class Config: | ||
| json_encoders = JSON_ENCODERS | ||
| use_enum_values = True | ||
|
|
||
|
|
||
| class NotificationOccurrence(BaseModel): | ||
| """A single occurrence represented by a grouped notification.""" | ||
|
|
||
| occurred_at: datetime = Field(default_factory=lambda: datetime.now(tz=timezone.utc)) | ||
| summary: str | None = Field(None, max_length=1000) | ||
| message: str | None = Field(None, max_length=5000) | ||
| level: NotificationLevel = Field(NotificationLevel.NORMAL) | ||
| is_new: bool = Field( | ||
| False, | ||
| description="Whether this occurrence arrived since the notification was last read.", | ||
| ) | ||
|
|
||
| class Config: | ||
| json_encoders = JSON_ENCODERS | ||
| use_enum_values = True | ||
|
|
||
|
|
||
| class Notification(Entry): | ||
| """A notification addressed to one user.""" | ||
|
|
||
| type: str = Field("notifications", const=True) | ||
| recipient_id: PyObjectId = Field(..., description="ID of the user receiving the notification") | ||
| title: str = Field(..., min_length=1, max_length=200) | ||
| summary: str | None = Field( | ||
| None, | ||
| max_length=1000, | ||
| description="Short text shown in compact notification lists.", | ||
| ) | ||
| message: str | None = Field(None, max_length=5000) | ||
| level: NotificationLevel = Field(NotificationLevel.NORMAL) | ||
| created_at: datetime = Field(default_factory=lambda: datetime.now(tz=timezone.utc)) | ||
| created_by: PyObjectId | None = Field(None, description="User ID that created the notification") | ||
| read_at: datetime | None = None | ||
| archived_at: datetime | None = None | ||
| grouping: NotificationGrouping | None = None | ||
| occurrence_count: int = Field(1, ge=1) | ||
| last_occurred_at: datetime = Field(default_factory=lambda: datetime.now(tz=timezone.utc)) | ||
| occurrences: list[NotificationOccurrence] | None = Field( | ||
| None, | ||
| description="Individual occurrence details for grouped notifications.", | ||
| ) | ||
|
|
||
| class Config(Entry.Config): | ||
| use_enum_values = True |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,163 @@ | ||
| from datetime import datetime, timedelta, timezone | ||
| from typing import Any | ||
|
|
||
| from bson import ObjectId | ||
| from pymongo import ReturnDocument | ||
|
|
||
| from pydatalab.config import CONFIG | ||
| from pydatalab.logger import LOGGER | ||
| from pydatalab.models.notifications import ( | ||
| Notification, | ||
| NotificationGrouping, | ||
| NotificationGroupPolicy, | ||
| NotificationLevel, | ||
| NotificationOccurrence, | ||
| ) | ||
| from pydatalab.models.utils import PyObjectId | ||
| from pydatalab.mongo import flask_mongo | ||
|
|
||
|
|
||
| def _max_level( | ||
| current_level: NotificationLevel | str | None, new_level: NotificationLevel | str | ||
| ) -> str: | ||
| new_notification_level = NotificationLevel(new_level) | ||
| if current_level is None: | ||
| return new_notification_level.value | ||
|
|
||
| current_notification_level = NotificationLevel(current_level) | ||
| if new_notification_level.priority > current_notification_level.priority: | ||
| return new_notification_level.value | ||
|
|
||
| return current_notification_level.value | ||
|
|
||
|
|
||
| def _find_grouped_notification( | ||
| *, | ||
| recipient_id: ObjectId, | ||
| title: str, | ||
| grouping: NotificationGrouping, | ||
| now: datetime, | ||
| session: Any | None = None, | ||
| ) -> dict | None: | ||
| query: dict[str, object] = { | ||
| "recipient_id": recipient_id, | ||
| "title": title, | ||
| "grouping.key": grouping.key, | ||
| "grouping.policy": grouping.policy, | ||
| "$expr": {"$lt": ["$occurrence_count", "$grouping.max_occurrences"]}, | ||
| "archived_at": None, | ||
| } | ||
| if NotificationGroupPolicy(grouping.policy) == NotificationGroupPolicy.WINDOW: | ||
| query["grouping.window_seconds"] = grouping.window_seconds | ||
| query["last_occurred_at"] = { | ||
| "$gte": now - timedelta(seconds=int(grouping.window_seconds or 0)) | ||
| } | ||
|
|
||
| return flask_mongo.db.notifications.find_one( | ||
| query, | ||
| sort=[("last_occurred_at", -1), ("created_at", -1)], | ||
| session=session, | ||
| ) | ||
|
|
||
|
|
||
| def _insert_notification(notification: Notification, *, session: Any | None = None) -> Notification: | ||
| result = flask_mongo.db.notifications.insert_one( | ||
| notification.dict(by_alias=True, exclude_none=True), | ||
| session=session, | ||
| ) | ||
| notification.immutable_id = result.inserted_id | ||
| return notification | ||
|
|
||
|
|
||
| def create_notification_with_result( | ||
| *, | ||
| recipient_id: str | ObjectId | PyObjectId, | ||
| title: str, | ||
| message: str | None = None, | ||
| summary: str | None = None, | ||
| level: NotificationLevel | str = NotificationLevel.NORMAL, | ||
| created_by: str | ObjectId | PyObjectId | None = None, | ||
| grouping: NotificationGrouping | dict[str, object] | None = None, | ||
| session: Any | None = None, | ||
| ) -> tuple[Notification, bool] | None: | ||
| """Create or group an in-app notification if the feature is enabled. | ||
|
|
||
| Returns: | ||
| A tuple of ``(notification, created)`` when a notification is created or | ||
| grouped. ``created`` is ``True`` when a new notification document was | ||
| inserted and ``False`` when the notification was folded into an existing | ||
| grouped notification. Returns ``None`` when notifications are disabled. | ||
| """ | ||
|
|
||
| if not CONFIG.ENABLE_NOTIFICATIONS: | ||
| LOGGER.debug("Notifications are disabled; not creating notification %r", title) | ||
| return None | ||
|
|
||
| now = datetime.now(tz=timezone.utc) | ||
| recipient_object_id = ObjectId(recipient_id) | ||
|
|
||
| if grouping is None: | ||
| notification = Notification( | ||
| recipient_id=recipient_object_id, | ||
| title=title, | ||
| summary=summary, | ||
| message=message, | ||
| level=level, | ||
| created_by=ObjectId(created_by) if created_by else None, | ||
| occurrence_count=1, | ||
| last_occurred_at=now, | ||
| ) | ||
| return _insert_notification(notification, session=session), True | ||
|
|
||
| if isinstance(grouping, dict): | ||
| grouping = NotificationGrouping(**grouping) | ||
|
|
||
| occurrence = NotificationOccurrence( | ||
| occurred_at=now, | ||
| message=message, | ||
| summary=summary, | ||
| level=level, | ||
| is_new=True, | ||
| ) | ||
| grouped_notification = _find_grouped_notification( | ||
| recipient_id=recipient_object_id, | ||
| title=title, | ||
| grouping=grouping, | ||
| now=now, | ||
| session=session, | ||
| ) | ||
|
|
||
| if grouped_notification is not None: | ||
| mongo_update = { | ||
| "$inc": {"occurrence_count": 1}, | ||
| "$set": { | ||
| "message": message, | ||
| "summary": summary, | ||
| "last_occurred_at": now, | ||
| "level": _max_level(grouped_notification.get("level"), level), | ||
| }, | ||
| "$push": {"occurrences": occurrence.dict(exclude_none=True)}, | ||
| "$unset": {"read_at": ""}, | ||
| } | ||
| updated_notification = flask_mongo.db.notifications.find_one_and_update( | ||
| {"_id": grouped_notification["_id"]}, | ||
| mongo_update, | ||
| return_document=ReturnDocument.AFTER, | ||
| session=session, | ||
| ) | ||
|
davidwaroquiers marked this conversation as resolved.
|
||
| return Notification(**updated_notification), False | ||
|
|
||
| notification = Notification( | ||
| recipient_id=recipient_object_id, | ||
| title=title, | ||
| summary=summary, | ||
| message=message, | ||
| level=level, | ||
| created_by=ObjectId(created_by) if created_by else None, | ||
| grouping=grouping, | ||
| occurrence_count=1, | ||
| last_occurred_at=now, | ||
| occurrences=[occurrence], | ||
| ) | ||
|
|
||
| return _insert_notification(notification, session=session), True | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.