Skip to content

Feature: Dynamic resource notices #2087

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

Merged
merged 21 commits into from
Mar 31, 2023
Merged
Show file tree
Hide file tree
Changes from 18 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
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
2 changes: 2 additions & 0 deletions frontend/amundsen_application/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
from amundsen_application.api.preview.v0 import preview_blueprint
from amundsen_application.api.quality.v0 import quality_blueprint
from amundsen_application.api.search.v1 import search_blueprint
from amundsen_application.api.notice.v0 import notices_blueprint
from amundsen_application.api.v0 import blueprint
from amundsen_application.deprecations import process_deprecations

Expand Down Expand Up @@ -86,6 +87,7 @@ def create_app(config_module_class: str = None, template_folder: str = None) ->
app.register_blueprint(preview_blueprint)
app.register_blueprint(quality_blueprint)
app.register_blueprint(search_blueprint)
app.register_blueprint(notices_blueprint)
app.register_blueprint(api_bp)
app.register_blueprint(dashboard_preview_blueprint)
init_routes(app)
Expand Down
2 changes: 2 additions & 0 deletions frontend/amundsen_application/api/notice/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Copyright Contributors to the Amundsen project.
# SPDX-License-Identifier: Apache-2.0
64 changes: 64 additions & 0 deletions frontend/amundsen_application/api/notice/v0.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
# Copyright Contributors to the Amundsen project.
# SPDX-License-Identifier: Apache-2.0

import logging
import json

from http import HTTPStatus
from typing import cast


from flask import Response, jsonify, make_response, request, current_app as app
from flask.blueprints import Blueprint
from marshmallow import ValidationError
from werkzeug.utils import import_string

from amundsen_application.api.utils.request_utils import get_query_param
from amundsen_application.base.base_notice_client import BaseNoticeClient

LOGGER = logging.getLogger(__name__)
NOTICE_CLIENT_INSTANCE = None

notices_blueprint = Blueprint('notices', __name__, url_prefix='/api/notices/v0')


def get_notice_client() -> BaseNoticeClient:
global NOTICE_CLIENT_INSTANCE
if NOTICE_CLIENT_INSTANCE is None and app.config['NOTICE_CLIENT'] is not None:
notice_client_class = import_string(app.config['NOTICE_CLIENT'])
NOTICE_CLIENT_INSTANCE = notice_client_class()
return cast(BaseNoticeClient, NOTICE_CLIENT_INSTANCE)


@notices_blueprint.route('/table', methods=['GET'])
def get_table_notices_summary() -> Response:
global NOTICE_CLIENT_INSTANCE
try:
client = get_notice_client()
if client is not None:
return _get_table_notices_summary_client()
payload = jsonify({'notices': {}, 'msg': 'A client for retrieving resource notices must be configured'})
return make_response(payload, HTTPStatus.NOT_IMPLEMENTED)
except Exception as e:
message = 'Encountered exception: ' + str(e)
LOGGER.exception(message)
payload = jsonify({'notices': {}, 'msg': message})
return make_response(payload, HTTPStatus.INTERNAL_SERVER_ERROR)


def _get_table_notices_summary_client() -> Response:
client = get_notice_client()
table_key = get_query_param(request.args, 'key')
response = client.get_table_notices_summary(table_key=table_key)
status_code = response.status_code
if status_code == HTTPStatus.OK:
try:
notices = json.loads(response.data).get('notices')
payload = jsonify({'notices': notices, 'msg': 'Success'})
except ValidationError as err:
raise Exception(f"Notices client didn't return a valid ResourceNotice object. {err}")
else:
message = f'Encountered error: Notice client request failed with code {status_code}'
LOGGER.error(message)
payload = jsonify({'notices': {}, 'msg': message})
return make_response(payload, status_code)
21 changes: 21 additions & 0 deletions frontend/amundsen_application/base/base_notice_client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Copyright Contributors to the Amundsen project.
# SPDX-License-Identifier: Apache-2.0

from abc import ABC
from abc import abstractmethod
from flask import Response


class BaseNoticeClient(ABC):
"""
Abstract interface for a client that provides alerts affecting a given table.
"""

@abstractmethod
def get_table_notices_summary(self, *, table_key: str) -> Response:
"""
Returns table alerts response for a given table URI
:param table_key: Table key for table to get alerts for
:return: flask Response object
"""
raise NotImplementedError
3 changes: 3 additions & 0 deletions frontend/amundsen_application/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,9 @@ class Config:
# Maps to a class path and name
ANNOUNCEMENT_CLIENT = os.getenv('ANNOUNCEMENT_CLIENT', None) # type: Optional[str]

# Settings for resource Notice client
NOTICE_CLIENT = os.getenv('NOTICE_CLIENT', None) # type: Optional[str]

# Settings for Issue tracker integration
ISSUE_LABELS = [] # type: List[str]
ISSUE_TRACKER_API_TOKEN = None # type: str
Expand Down
11 changes: 11 additions & 0 deletions frontend/amundsen_application/models/notice.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Copyright Contributors to the Amundsen project.
# SPDX-License-Identifier: Apache-2.0

from dataclasses import dataclass


@dataclass
class ResourceNotice:
severity: int
message: str
details: dict
1 change: 1 addition & 0 deletions frontend/amundsen_application/static/css/_popovers.scss
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@
.modal-body {
text-align: left;
padding: $spacer-2 $spacer-3;
overflow: auto;
}

.modal-footer {
Expand Down
159 changes: 159 additions & 0 deletions frontend/amundsen_application/static/js/components/Alert/Alert.tsx
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is this file meant to replace this? https://github.com/amundsen-io/amundsen/blob/main/frontend/amundsen_application/static/js/components/Alert/index.tsx

I remember reviewing a few small changes recently that seem to have been made in the index.tsx file but not here. not sure if this one just hasn't been updated, and if so should the index file be deleted as part of this PR?

Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
// Copyright Contributors to the Amundsen project.
// SPDX-License-Identifier: Apache-2.0

import * as React from 'react';
import SanitizedHTML from 'react-sanitized-html';
import { Modal } from 'react-bootstrap';

import { IconSizes } from 'interfaces';
import { NoticeSeverity } from 'config/config-types';
import { AlertIcon, InformationIcon } from 'components/SVGIcons';
import { DefinitionList } from 'components/DefinitionList';

import './styles.scss';

const SEVERITY_TO_COLOR_MAP = {
[NoticeSeverity.INFO]: '#3a97d3', // cyan50
[NoticeSeverity.WARNING]: '#ffb146', // $amber50
[NoticeSeverity.ALERT]: '#b8072c', // $red70
};
const SEVERITY_TO_SEVERITY_CLASS = {
[NoticeSeverity.INFO]: 'is-info',
[NoticeSeverity.WARNING]: 'is-warning',
[NoticeSeverity.ALERT]: 'is-alert',
};
const OPEN_PAYLOAD_CTA = 'See details';
const PAYLOAD_MODAL_TITLE = 'Summary';
const PAYLOAD_MODAL_CLOSE_BTN = 'Close';

export interface AlertProps {
/** Message to show in the alert */
message: string | React.ReactNode;
/** Severity of the alert (info, warning, or alert) */
severity?: NoticeSeverity;
/** Link passed to set as the action (for routing links) */
actionLink?: React.ReactNode;
/** Text of the link action */
actionText?: string;
/** Href for the link action */
actionHref?: string;
/** Callback to call when the action is clicked */
onAction?: (event: React.MouseEvent<HTMLButtonElement>) => void;
/** Optional extra info to render in a modal */
payload?: Record<string, string>;
}

export const Alert: React.FC<AlertProps> = ({
message,
severity = NoticeSeverity.WARNING,
onAction,
actionText,
actionHref,
actionLink,
payload,
}: AlertProps) => {
const [showPayloadModal, setShowPayloadModal] = React.useState(false);
let action: null | React.ReactNode = null;

const handleSeeDetails = (e: React.MouseEvent<HTMLButtonElement>) => {
onAction?.(e);
setShowPayloadModal(true);
};
const handleModalClose = () => {
setShowPayloadModal(false);
};

if (payload) {
action = (
<button
type="button"
className="btn btn-link btn-payload"
onClick={handleSeeDetails}
>
{OPEN_PAYLOAD_CTA}
</button>
);
}

if (actionText && onAction) {
action = (
<button type="button" className="btn btn-link" onClick={onAction}>
{actionText}
</button>
);
}

if (actionText && actionHref) {
action = (
<a className="action-link" href={actionHref}>
{actionText}
</a>
);
}

if (actionLink) {
action = actionLink;
}

let iconComponent: React.ReactNode = null;

if (severity === NoticeSeverity.INFO) {
iconComponent = (
<InformationIcon
fill={SEVERITY_TO_COLOR_MAP[severity]}
size={IconSizes.REGULAR}
/>
);
} else {
iconComponent = (
<AlertIcon
stroke={SEVERITY_TO_COLOR_MAP[severity]}
size={IconSizes.SMALL}
/>
);
}

// If we receive a string, we want to sanitize any html inside
const formattedMessage =
typeof message === 'string' ? <SanitizedHTML html={message} /> : message;

const payloadDefinitions = payload
? Object.keys(payload).map((key) => ({
term: key,
description: payload[key],
}))
: null;

return (
<div className={`alert ${SEVERITY_TO_SEVERITY_CLASS[severity]}`}>
{iconComponent}
<p className="alert-message">{formattedMessage}</p>
{action && <span className="alert-action">{action}</span>}
{payloadDefinitions && (
<Modal
className="alert-payload-modal"
show={showPayloadModal}
onHide={handleModalClose}
>
<Modal.Header closeButton onHide={handleModalClose}>
<Modal.Title>{PAYLOAD_MODAL_TITLE}</Modal.Title>
</Modal.Header>
<Modal.Body>
<DefinitionList definitions={payloadDefinitions} termWidth={120} />
</Modal.Body>
<Modal.Footer>
<button
className="btn btn-primary payload-modal-close"
type="button"
onClick={handleModalClose}
>
{PAYLOAD_MODAL_CLOSE_BTN}
</button>
</Modal.Footer>
</Modal>
)}
</div>
);
};

export default Alert;
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// Copyright Contributors to the Amundsen project.
// SPDX-License-Identifier: Apache-2.0

import * as React from 'react';

import { NoticeType } from 'config/config-types';
import { Alert } from './Alert';

export interface AlertListProps {
notices: NoticeType[];
}

export const AlertList: React.FC<AlertListProps> = ({ notices }) => {
if (!notices.length) {
return null;
}

return (
<div className="alert-list">
{notices.map((notice, idx) => (
<Alert
key={idx}
message={notice.messageHtml}
severity={notice.severity}
payload={notice.payload}
/>
))}
</div>
);
};
Loading