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

Add spending limit notifications #11556

Merged
merged 2 commits into from
Jul 22, 2022
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 components/dashboard/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ import SelectIDEModal from "./settings/SelectIDEModal";
import { StartPage, StartPhase } from "./start/StartPage";
import { isGitpodIo } from "./utils";
import { BlockedRepositories } from "./admin/BlockedRepositories";
import { AppNotifications } from "./AppNotifications";

const Setup = React.lazy(() => import(/* webpackPrefetch: true */ "./Setup"));
const Workspaces = React.lazy(() => import(/* webpackPrefetch: true */ "./workspaces/Workspaces"));
Expand Down Expand Up @@ -346,6 +347,7 @@ function App() {
<Route>
<div className="container">
<Menu />
<AppNotifications />
<Switch>
<Route path={projectsPathNew} exact component={NewProject} />
<Route path="/open" exact component={Open} />
Expand Down
76 changes: 76 additions & 0 deletions components/dashboard/src/AppNotifications.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/**
* Copyright (c) 2022 Gitpod GmbH. All rights reserved.
* Licensed under the GNU Affero General Public License (AGPL).
* See License-AGPL.txt in the project root for license information.
*/

import { useEffect, useState } from "react";
import Alert from "./components/Alert";
import { getGitpodService } from "./service/service";

const KEY_APP_NOTIFICATIONS = "KEY_APP_NOTIFICATIONS";

export function AppNotifications() {
const [notifications, setNotifications] = useState<string[]>([]);

useEffect(() => {
let localState = getLocalStorageObject(KEY_APP_NOTIFICATIONS);
if (Array.isArray(localState)) {
setNotifications(localState);
return;
}
(async () => {
const serverState = await getGitpodService().server.getNotifications();
setNotifications(serverState);
setLocalStorageObject(KEY_APP_NOTIFICATIONS, serverState);
})();
}, []);

const topNotification = notifications[0];
if (topNotification === undefined) {
return null;
}

const dismissNotification = () => {
removeLocalStorageObject(KEY_APP_NOTIFICATIONS);
setNotifications([]);
};

return (
<div className="app-container pt-2">
<Alert
type={"warning"}
closable={true}
onClose={() => dismissNotification()}
showIcon={true}
className="flex rounded mb-2 w-full"
>
<span>{topNotification}</span>
</Alert>
</div>
);
}

function getLocalStorageObject(key: string): any {
try {
const string = window.localStorage.getItem(key);
if (!string) {
return;
}
return JSON.parse(string);
} catch (error) {
return;
}
}

function removeLocalStorageObject(key: string): void {
window.localStorage.removeItem(key);
}

function setLocalStorageObject(key: string, object: Object): void {
try {
window.localStorage.setItem(key, JSON.stringify(object));
} catch (error) {
console.error("Setting localstorage item failed", key, object, error);
}
}
11 changes: 10 additions & 1 deletion components/dashboard/src/components/Alert.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ export interface AlertProps {
// Without background color, default false
light?: boolean;
closable?: boolean;
onClose?: () => void;
showIcon?: boolean;
icon?: React.ReactNode;
children?: React.ReactNode;
Expand Down Expand Up @@ -80,7 +81,15 @@ export default function Alert(props: AlertProps) {
<span className="flex-1 text-left">{props.children}</span>
{props.closable && (
<span className={`mt-1 ml-4 h-4 w-4`}>
<XSvg onClick={() => setVisible(false)} className="w-3 h-4 cursor-pointer"></XSvg>
<XSvg
onClick={() => {
setVisible(false);
if (props.onClose) {
props.onClose();
}
}}
className="w-3 h-4 cursor-pointer"
></XSvg>
</span>
)}
</div>
Expand Down
5 changes: 5 additions & 0 deletions components/gitpod-protocol/src/gitpod-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,11 @@ export interface GitpodServer extends JsonRpcServer<GitpodClient>, AdminServer,
trackEvent(event: RemoteTrackMessage): Promise<void>;
trackLocation(event: RemotePageMessage): Promise<void>;
identifyUser(event: RemoteIdentifyMessage): Promise<void>;

/**
* Frontend notifications
*/
getNotifications(): Promise<string[]>;
}

export interface RateLimiterError {
Expand Down
20 changes: 20 additions & 0 deletions components/server/ee/src/workspace/gitpod-server-impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2096,6 +2096,26 @@ export class GitpodServerEEImpl extends GitpodServerImpl {
});
}

async getNotifications(ctx: TraceContext): Promise<string[]> {
const result = await super.getNotifications(ctx);
const user = this.checkAndBlockUser("getNotifications");
if (user.usageAttributionId) {
Copy link
Member

Choose a reason for hiding this comment

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

This has to be replaced by the getBillingMode(user) method. But as it's not there it, this is fine.

const allSessions = await this.listBilledUsage(ctx, user.usageAttributionId);
const totalUsage = allSessions.map((s) => s.credits).reduce((a, b) => a + b, 0);
Copy link
Member

Choose a reason for hiding this comment

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

Ideally we'd get that from the service as well, but we can replace that once we do.

const costCenter = await this.costCenterDB.findById(user.usageAttributionId);
if (costCenter) {
if (totalUsage > costCenter.spendingLimit) {
result.unshift("The spending limit is reached.");
} else if (totalUsage > 0.8 * costCenter.spendingLimit * 0.8) {
result.unshift("The spending limit is almost reached.");
}
} else {
log.warn("No costcenter found.", { userId: user.id, attributionId: user.usageAttributionId });
}
}
return result;
}

async listBilledUsage(ctx: TraceContext, attributionId: string): Promise<BillableSession[]> {
traceAPIParams(ctx, { attributionId });
const user = this.checkAndBlockUser("listBilledUsage");
Expand Down
1 change: 1 addition & 0 deletions components/server/src/auth/rate-limiter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,7 @@ function getConfig(config: RateLimiterConfig): RateLimiterConfig {
setUsageAttribution: { group: "default", points: 1 },
getSpendingLimitForTeam: { group: "default", points: 1 },
setSpendingLimitForTeam: { group: "default", points: 1 },
getNotifications: { group: "default", points: 1 },
};

return {
Expand Down
5 changes: 5 additions & 0 deletions components/server/src/workspace/gitpod-server-impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3243,4 +3243,9 @@ export class GitpodServerImpl implements GitpodServerWithTracing, Disposable {
return this.imagebuilderClientProvider.getClient(user, workspace, instance);
}
}

async getNotifications(ctx: TraceContext): Promise<string[]> {
this.checkAndBlockUser("getNotifications");
return [];
}
}