Skip to content
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
54 changes: 54 additions & 0 deletions apps/dashboard/src/@/api/usage/rpc.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import "server-only";
import { unstable_cache } from "next/cache";

export type RPCUsageDataItem = {
date: string;
usageType: "included" | "overage" | "rate-limit";
count: string;
};

export const fetchRPCUsage = unstable_cache(
async (params: {
teamId: string;
projectId?: string;
authToken: string;
from: string;
to: string;
period: "day" | "week" | "month" | "year" | "all";
}) => {
const analyticsEndpoint = process.env.ANALYTICS_SERVICE_URL as string;
const url = new URL(`${analyticsEndpoint}/v2/rpc/usage-types`);
url.searchParams.set("teamId", params.teamId);
if (params.projectId) {
url.searchParams.set("projectId", params.projectId);
}
url.searchParams.set("from", params.from);
url.searchParams.set("to", params.to);
url.searchParams.set("period", params.period);

const res = await fetch(url, {
headers: {
Authorization: `Bearer ${params.authToken}`,
},
});

if (!res.ok) {
const error = await res.text();
return {
ok: false as const,
error: error,
};
}

const resData = await res.json();

return {
ok: true as const,
data: resData.data as RPCUsageDataItem[],
};
},
["nebula-analytics"],
{
revalidate: 60 * 60, // 1 hour
},
);
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { getInAppWalletUsage, getUserOpUsage } from "@/api/analytics";
import type { Team } from "@/api/team";
import type { TeamSubscription } from "@/api/team-subscription";
import type { RPCUsageDataItem } from "@/api/usage/rpc";
import { ThirdwebBarChart } from "@/components/blocks/charts/bar-chart";
import { Button } from "@/components/ui/button";
import type {
Account,
Expand Down Expand Up @@ -28,6 +30,7 @@ type UsageProps = {
image: string | null;
slug: string;
}[];
rpcUsage: RPCUsageDataItem[];
};

const compactNumberFormatter = new Intl.NumberFormat("en-US", {
Expand All @@ -42,24 +45,8 @@ export const Usage: React.FC<UsageProps> = ({
team,
client,
projects,
rpcUsage,
}) => {
// TODO - get this from team instead of account
const rpcMetrics = useMemo(() => {
if (!usageData) {
return {};
}

return {
title: "Unlimited Requests",
total: (
<span className="text-muted-foreground">
{compactNumberFormatter.format(usageData.rateLimits.rpc)} Requests Per
Second
</span>
),
};
}, [usageData]);

const gatewayMetrics = useMemo(() => {
if (!usageData) {
return {};
Expand Down Expand Up @@ -91,6 +78,37 @@ export const Usage: React.FC<UsageProps> = ({

const storageUsage = team.capabilities.storage.upload;

const rpcUsageData = useMemo(() => {
const mappedRPCUsage = rpcUsage.reduce(
(acc, curr) => {
switch (curr.usageType) {
case "rate-limit":
acc[curr.date] = {
...(acc[curr.date] || {}),
"rate-limit":
(acc[curr.date]?.["rate-limit"] || 0) + Number(curr.count),
included: acc[curr.date]?.included || 0,
};
break;
default:
acc[curr.date] = {
...(acc[curr.date] || {}),
"rate-limit": acc[curr.date]?.["rate-limit"] || 0,
included: (acc[curr.date]?.included || 0) + Number(curr.count),
};
break;
Comment on lines +81 to +99
Copy link
Contributor

Choose a reason for hiding this comment

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

There's a potential issue in the reduce function's switch statement. When processing multiple records for the same date with different usageType values, the current implementation might not correctly accumulate values.

In both switch cases, the code should add to existing values rather than potentially overwriting them. Consider refactoring to ensure proper accumulation:

acc[curr.date] = {
  ...(acc[curr.date] || {}),
  "rate-limit": (acc[curr.date]?.["rate-limit"] || 0) + (curr.usageType === "rate-limit" ? Number(curr.count) : 0),
  included: (acc[curr.date]?.included || 0) + (curr.usageType !== "rate-limit" ? Number(curr.count) : 0)
};

This approach would handle all usageType values in a single consistent pattern, ensuring values are properly accumulated regardless of processing order.

Suggested change
const rpcUsageData = useMemo(() => {
const mappedRPCUsage = rpcUsage.reduce(
(acc, curr) => {
switch (curr.usageType) {
case "rate-limit":
acc[curr.date] = {
...(acc[curr.date] || {}),
"rate-limit":
(acc[curr.date]?.["rate-limit"] || 0) + Number(curr.count),
included: acc[curr.date]?.included || 0,
};
break;
default:
acc[curr.date] = {
...(acc[curr.date] || {}),
"rate-limit": acc[curr.date]?.["rate-limit"] || 0,
included: (acc[curr.date]?.included || 0) + Number(curr.count),
};
break;
const rpcUsageData = useMemo(() => {
const mappedRPCUsage = rpcUsage.reduce(
(acc, curr) => {
acc[curr.date] = {
...(acc[curr.date] || {}),
"rate-limit": (acc[curr.date]?.["rate-limit"] || 0) + (curr.usageType === "rate-limit" ? Number(curr.count) : 0),
included: (acc[curr.date]?.included || 0) + (curr.usageType !== "rate-limit" ? Number(curr.count) : 0)
};
return acc;
},

Spotted by Diamond

Is this helpful? React 👍 or 👎 to let us know.

}
return acc;
},
{} as Record<string, { included: number; "rate-limit": number }>,
);

return Object.entries(mappedRPCUsage).map(([date, usage]) => ({
time: new Date(date).getTime(),
...usage,
}));
}, [rpcUsage]);

return (
<div className="flex grow flex-col gap-8">
<InAppWalletUsersChartCard
Expand All @@ -117,10 +135,26 @@ export const Usage: React.FC<UsageProps> = ({
variant="team"
/>

<UsageCard
{...rpcMetrics}
name="RPC"
description="Amount of RPC requests allowed per second in your plan"
<ThirdwebBarChart
header={{
title: "RPC Requests",
description: `Your plan allows for ${usageData.rateLimits.rpc} requests per second`,
titleClassName: "text-xl mb-0.5",
}}
data={rpcUsageData}
isPending={false}
variant="stacked"
config={{
included: {
label: "RPC Requests",
color: "hsl(var(--chart-1))",
},
"rate-limit": {
label: "Rate Limited Requests",
color: "hsl(var(--chart-3))",
},
}}
chartClassName="aspect-[1.5] lg:aspect-[4]"
/>

<UsageCard
Expand Down
23 changes: 21 additions & 2 deletions apps/dashboard/src/app/team/[team_slug]/(team)/~/usage/page.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import { getProjects } from "@/api/projects";
import { getTeamBySlug } from "@/api/team";
import { getTeamSubscriptions } from "@/api/team-subscription";
import { fetchRPCUsage } from "@/api/usage/rpc";
import { getThirdwebClient } from "@/constants/thirdweb.server";
import { normalizeTimeISOString } from "lib/time";
import { redirect } from "next/navigation";
import { getValidAccount } from "../../../../../account/settings/getAccount";
import { getAuthToken } from "../../../../../api/lib/getAuthToken";
import { loginRedirect } from "../../../../../login/loginRedirect";
import { getAccountUsage } from "./getAccountUsage";
import { Usage } from "./overview/components/Usage";

Expand All @@ -24,13 +27,28 @@ export default async function Page(props: {
redirect("/team");
}

const [accountUsage, subscriptions, projects] = await Promise.all([
if (!authToken) {
loginRedirect(`/team/${params.team_slug}/~/usage`);
}

const [accountUsage, subscriptions, projects, rpcUsage] = await Promise.all([
getAccountUsage(),
getTeamSubscriptions(team.slug),
getProjects(team.slug),
fetchRPCUsage({
authToken,
period: "day",
// 7 days ago
from: normalizeTimeISOString(
new Date(Date.now() - 1000 * 60 * 60 * 24 * 7),
),
// now
to: normalizeTimeISOString(new Date()),
teamId: team.id,
}),
]);

if (!accountUsage || !subscriptions || !authToken) {
if (!accountUsage || !subscriptions) {
return (
<div className="flex min-h-[350px] items-center justify-center rounded-lg border p-4 text-destructive-text">
Something went wrong. Please try again later.
Expand All @@ -48,6 +66,7 @@ export default async function Page(props: {
account={account}
team={team}
client={client}
rpcUsage={rpcUsage.ok ? rpcUsage.data : []}
projects={projects.map((project) => ({
id: project.id,
name: project.name,
Expand Down
Loading