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

Status endpoints #58

Merged
merged 17 commits into from
Apr 6, 2020
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
2 changes: 2 additions & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
.git
.env
node_modules
Dockerfile
.dockerignore
npm-debug.log
.storybook
.vscode
14 changes: 13 additions & 1 deletion env.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,15 @@ const CORS_PROXY_PREFIX = process.env.CORS_PROXY_PREFIX || '/cors_proxy';
const CONFIG_DIR = process.env.CONFIG_DIR || './config';
const CONFIG_CACHE_TTL_SECONDS = process.env.CONFIG_CACHE_TTL_SECONDS || '60';

// Defines a file to be required which will provide implementations for
// any user-definable code.
const PLUGINS_MODULE = process.env.PLUGINS_MODULE;

// Optional URL which will provide information about system status. This is used
// to show informational banners to the user.
// If it has no protocol, it will be treated as relative to window.location.origin
const STATUS_URL = process.env.STATUS_URL;

module.exports = {
ADMIN_API_URL,
BASE_URL,
Expand All @@ -23,10 +32,13 @@ module.exports = {
CONFIG_DIR,
CORS_PROXY_PREFIX,
NODE_ENV,
PLUGINS_MODULE,
STATUS_URL,
processEnv: {
ADMIN_API_URL,
BASE_URL,
CORS_PROXY_PREFIX,
NODE_ENV
NODE_ENV,
STATUS_URL
}
};
7 changes: 7 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,24 @@ const fs = require('fs');
const morgan = require('morgan');
const express = require('express');
const env = require('./env');
const { applyMiddleware } = require('./plugins');

const corsProxy = require('./corsProxy.js');

const app = express();

// Enable logging for HTTP access
app.use(morgan('combined'));
app.use(express.json());

app.get(`${env.BASE_URL}/healthz`, (_req, res) => res.status(200).send());
app.use(corsProxy(`${env.BASE_URL}${env.CORS_PROXY_PREFIX}`));

if (typeof applyMiddleware === 'function') {
console.log('Found middleware plugins, applying...');
applyMiddleware(app);
}

if (process.env.NODE_ENV === 'production') {
const path = require('path');
const expressStaticGzip = require('express-static-gzip');
Expand Down
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@
"@types/html-webpack-plugin": "^2.28.0",
"@types/jest": "^25.1.2",
"@types/js-yaml": "^3.10.1",
"@types/linkify-it": "^2.1.0",
"@types/lodash": "^4.14.68",
"@types/long": "^3.0.32",
"@types/lossless-json": "^1.0.0",
Expand Down Expand Up @@ -143,6 +144,7 @@
"identity-obj-proxy": "^3.0.0",
"intersection-observer": "^0.7.0",
"jest": "^24.9.0",
"linkify-it": "^2.2.0",
"lint-staged": "^7.0.4",
"lossless-json": "^1.0.3",
"memoize-one": "^5.0.0",
Expand Down
11 changes: 11 additions & 0 deletions plugins.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
const env = require('./env');

const { middleware } = env.PLUGINS_MODULE ? require(env.PLUGINS_MODULE) : {};

if (Array.isArray(middleware)) {
module.exports.applyMiddleware = app => middleware.forEach(m => m(app));
} else if (middleware !== undefined) {
console.log(
`Expected middleware to be of type Array, but got ${middleware} instead`
);
}
45 changes: 45 additions & 0 deletions src/common/linkify.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import * as LinkifyIt from 'linkify-it';
export const linkify = new LinkifyIt();

export type LinkifiedTextChunkType = 'text' | 'link';
export interface LinkifiedTextChunk {
type: LinkifiedTextChunkType;
text: string;
url?: string;
}

/** Detects any links in the given text and splits the string on the
* link boundaries, returning an array of text/link entries for each
* portion of the string.
*/
export function getLinkifiedTextChunks(text: string): LinkifiedTextChunk[] {
const matches = linkify.match(text);
if (matches === null) {
return [{ text, type: 'text' }];
}

const chunks: LinkifiedTextChunk[] = [];
let lastMatchEndIndex = 0;
matches.forEach(match => {
if (lastMatchEndIndex !== match.index) {
chunks.push({
text: text.substring(lastMatchEndIndex, match.index),
type: 'text'
});
}
chunks.push({
text: match.text,
type: 'link',
url: match.url
});
lastMatchEndIndex = match.lastIndex;
});
if (lastMatchEndIndex !== text.length) {
chunks.push({
text: text.substring(lastMatchEndIndex, text.length),
type: 'text'
});
}

return chunks;
}
50 changes: 50 additions & 0 deletions src/common/test/linkify.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { getLinkifiedTextChunks, LinkifiedTextChunk } from 'common/linkify';

function text(text: string): LinkifiedTextChunk {
return { text, type: 'text' };
}

function link(text: string): LinkifiedTextChunk {
return { text, url: text, type: 'link' };
}

describe('linkify/getLinkifiedTextChunks', () => {
const testCases: [string, LinkifiedTextChunk[]][] = [
['No match expected', [text('No match expected')]],
[
'Points to http://example.com',
[text('Points to '), link('http://example.com')]
],
[
'https://example.com link is at beginning',
[link('https://example.com'), text(' link is at beginning')]
],
[
'A link to http://example.com is in the middle',
[
text('A link to '),
link('http://example.com'),
text(' is in the middle')
]
],
[
'A link at the end to http://example.com',
[text('A link at the end to '), link('http://example.com')]
],
[
'A link to http://example.com and another link to https://flyte.org in the middle.',
[
text('A link to '),
link('http://example.com'),
text(' and another link to '),
link('https://flyte.org'),
text(' in the middle.')
]
]
];
testCases.forEach(([input, expected]) =>
it(`correctly splits: ${input}`, () => {
expect(getLinkifiedTextChunks(input)).toEqual(expected);
})
);
});
2 changes: 2 additions & 0 deletions src/components/App/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { env } from 'common/env';
import { debug, debugPrefix } from 'common/log';
import { APIContext, useAPIState } from 'components/data/apiContext';
import { LoginExpiredHandler } from 'components/Errors/LoginExpiredHandler';
import { SystemStatusBanner } from 'components/Notifications/SystemStatusBanner';
import { skeletonColor, skeletonHighlightColor } from 'components/Theme';
import { muiTheme } from 'components/Theme/muiTheme';
import * as React from 'react';
Expand Down Expand Up @@ -41,6 +42,7 @@ export const AppComponent: React.StatelessComponent<{}> = () => {
<LoginExpiredHandler />
</ErrorBoundary>
</Router>
<SystemStatusBanner />
</SkeletonTheme>
</APIContext.Provider>
</ThemeProvider>
Expand Down
151 changes: 151 additions & 0 deletions src/components/Notifications/SystemStatusBanner.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
import { ButtonBase, SvgIcon, Typography } from '@material-ui/core';
import Paper from '@material-ui/core/Paper';
import { makeStyles, Theme } from '@material-ui/core/styles';
import Close from '@material-ui/icons/Close';
import Info from '@material-ui/icons/Info';
import Warning from '@material-ui/icons/Warning';
import { WaitForData } from 'components/common';
import { LinkifiedText } from 'components/common/LinkifiedText';
import {
infoIconColor,
mutedButtonColor,
mutedButtonHoverColor,
warningIconColor
} from 'components/Theme';
import { StatusString, SystemStatus } from 'models/Common/types';
import * as React from 'react';
import { useSystemStatus } from './useSystemStatus';

const useStyles = makeStyles((theme: Theme) => ({
container: {
bottom: 0,
display: 'flex',
justifyContent: 'center',
left: 0,
// The parent container extends the full width of the page.
// We don't want it intercepting pointer events for visible items below it.
pointerEvents: 'none',
position: 'fixed',
padding: theme.spacing(2),
right: 0
},
closeButton: {
alignItems: 'center',
color: mutedButtonColor,
'&:hover': {
color: mutedButtonHoverColor
},
display: 'flex',
height: theme.spacing(3)
},
statusPaper: {
display: 'flex',
padding: theme.spacing(2),
pointerEvents: 'initial'
},
statusContentContainer: {
alignItems: 'flex-start',
display: 'flex',
maxWidth: theme.spacing(131)
},
statusClose: {
alignItems: 'flex-start',
display: 'flex',
flex: '0 0 auto'
},
statusIcon: {
alignItems: 'center',
display: 'flex',
flex: '0 0 auto',
lineHeight: `${theme.spacing(3)}px`
},
statusMessage: {
flex: '1 1 auto',
fontWeight: 'normal',
lineHeight: `${theme.spacing(3)}px`,
marginLeft: theme.spacing(2),
marginRight: theme.spacing(2)
}
}));

interface StatusConstantValues {
color: string;
IconComponent: typeof SvgIcon;
}

const InfoIcon = () => (
<Info data-testid="info-icon" htmlColor={infoIconColor} />
);

const WarningIcon = () => (
<Warning data-testid="warning-icon" htmlColor={warningIconColor} />
);

const statusIcons: Record<StatusString, React.ComponentType> = {
normal: InfoIcon,
degraded: WarningIcon,
down: WarningIcon
};

const StatusIcon: React.FC<{ status: StatusString }> = ({ status }) => {
const IconComponent = statusIcons[status] || statusIcons.normal;
return <IconComponent />;
};

const RenderSystemStatusBanner: React.FC<{
systemStatus: SystemStatus;
onClose: () => void;
}> = ({ systemStatus: { message, status }, onClose }) => {
const styles = useStyles();
return (
<div className={styles.container}>
<Paper
role="banner"
className={styles.statusPaper}
elevation={1}
square={true}
>
<div className={styles.statusIcon}>
<StatusIcon status={status} />
</div>
<div className={styles.statusContentContainer}>
<Typography variant="h6" className={styles.statusMessage}>
<LinkifiedText text={message} />
</Typography>
</div>
<div className={styles.statusClose}>
<ButtonBase
aria-label="Close"
className={styles.closeButton}
onClick={onClose}
>
<Close fontSize="small" />
</ButtonBase>
</div>
</Paper>
</div>
);
};

/** Fetches and renders the system status returned by issuing a GET to
* `env.STATUS_URL`. If the status includes a message, a dismissable toast
* will be rendered. Otherwise, nothing will be rendered.
*/
export const SystemStatusBanner: React.FC<{}> = () => {
const systemStatus = useSystemStatus();
const [dismissed, setDismissed] = React.useState(false);
const onClose = () => setDismissed(true);
if (dismissed) {
return null;
}
return (
<WaitForData {...systemStatus}>
{systemStatus.value.message ? (
<RenderSystemStatusBanner
systemStatus={systemStatus.value}
onClose={onClose}
/>
) : null}
</WaitForData>
);
};
Loading